Difference between dict and set (python)

后端 未结 3 587
难免孤独
难免孤独 2020-12-13 08:20

So, I know that this,

a = {}  # dict

Constructs an empty dictionary. Now, I also picked up that this,

b = {1, 2, 3}  # set
         


        
3条回答
  •  青春惊慌失措
    2020-12-13 09:07

    The syntax is not the same. Dictionaries used curly braces the first and you specify key-value pairs, where the key and value are separated by a colon:

    >>> {'foo': 'bar'}
    {'foo': 'bar'}
    >>> type(_)
    
    

    Sets were added to the language later on, and the {..} curly brace notation only names elements, not pairs:

    >>> {'foo'}
    set(['foo'])
    >>> type(_)
    
    

    Note that in Python 2, the interpreter echoes the object using the set() callable. That's also how you specify an empty set:

    >>> emptyset = set()
    

    In Python 3, the newer {..} notation is used when echoing the object, unless it is empty:

    >>> {'foo'}
    {'foo'}
    >>> _ - {'foo'}  # difference, removing the one element
    set()
    

    The set() type was added to the Python language in version 2.4 (see PEP 218), the curly brace syntax for set literals was added in Python 3 and back-ported to Python 2.7.

提交回复
热议问题