1. Create dictionary
Method①:
>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port': 80}
>> > dict1, dict2
({}, {'port': 80, 'name': 'earth'})
Method②: From Python 2.2 version onwards
>>> fdict = dict(([' x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}
Method ③:
From Python 2.3 version onwards, You can use the convenient built-in method fromkeys() to create a "default" dictionary where the elements have the same value (defaults to None if not given): ddict = { }.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}
>>>
> ;>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}
2. How to access Values in a dictionary
① To traverse a dictionary (usually using keys), you only need to loop through its keys, like this:
>>> dict2 = {'name': 'earth', 'port ': 80}
>>>
>>>> for key in dict2.keys():
... print 'key=%s, value=%s' % (key, dict2 [key])
...
key=name, value=earth
key=port, value=80
②Starting from Python 2.2
Traverse the dictionary in a for loop.
>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2:
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80
To get an element in the dictionary The value of can be obtained by using the dictionary key you are familiar with plus square brackets:
>>> dict2['name']
'earth'
>>>
>>> print 'host %s is running on port %d' %
... (dict2['name'], dict2['port'])
host earth is running on port 80
③All methods of dictionary. The methods has_key() and in and not in operators are all of Boolean type
>>> 'server' in dict2 # or dict2.has_key('server')
False
>>> 'name' in dict # or dict2.has_key('name')
True
>>> dict2['name']
'earth'
An example of mixing numbers and strings in a dictionary:
>>> dict3 = {}
>>> dict3[1] = 'abc'
>>> dict3['1'] = 3.14159
>>> dict3[3.2] = 'xyz'
>>> dict3
{3.2: 'xyz', 1: 'abc', '1': 3.14159}
3. Update the dictionary
adopt overwriting update
In the above example, dict2['name']= 'earth';
Update dict2['name']='abc';
4. Delete dictionary elements and dictionary
del dict2['name'] # Delete the entry with the key "name"
dict2.clear() # Delete all entries in dict2
del dict2 # Delete the entire dict2 dictionary
dict2.pop('name') # Delete and return the entry with key "name"
dict2 = {'name': 'earth', 'port' dict2.values()
[80, 'earth ']
>>>
>>> dict2.items()
[('port', 80), ('name', 'earth')]
>>>
> ;>> for eachKey in dict2.keys():
... print 'dict2 key', eachKey, 'has value', dict2[eachKey]
...
dict2 key port has value 80
dict2 key name has value earth
update() method can be used to add the contents of one dictionary to another dictionary
{'server': 'http', 'port': 80, 'host': 'venus'}
dict3.clear()
>>> dict3
>>> , y=2)
{'y': 2, 'x': 1}
>>> dict8 = dict(x=1, y=2)
>>> dict8
{'y ': 2, 'x': 1}
>>> dict9 = dict(**dict8)
>>> dict9
{'y': 2, 'x': 1}
dict9 = dict8.copy()
Dictionary built-in method:
Dictionary key value: dict9.keys()
Dictionary value: dict9.values()
All dictionary items: dict9.items()
Return dictionary value :dict9.get('y')
Table 7.2 Dictionary type methods
Method name operation
dict.cleara() deletes all elements in the dictionary
dict.copya() returns a copy of the dictionary (shallow copy)
dict.fromkeysc(seq,val=None) c creates and returns a new dictionary , use the elements in seq as the keys of the dictionary, and val as the initial values corresponding to all keys in the dictionary (if this value is not provided, it defaults to None)
dict.get(key,default=None)a for the dictionary The key key in dict returns its corresponding value value. If the key does not exist in the dictionary, the value of default is returned (note that the default value of parameter default is None)
dict.has_key(key) If key(key) Exists in the dictionary, returns True, otherwise returns False. After the introduction of in and not in in Python 2.2, this method has been almost abandoned, but it still provides a working interface.
dict.items() Returns a list containing tuples of (key, value) pairs in the dictionary
dict.keys() Returns a list containing the keys in the dictionary
dict.iter()d method iteritems(), iterkeys(), itervalues() are the same as their non-iterative counterparts, except that they return an iterator instead of a list.
dict.popc(key[, default]) c is similar to the method get(). If the key key exists in the dictionary, delete and return dict[key]. If the key key does not exist and no default value is given, raise KeyError exception.
dict.setdefault(key,default=None)e is similar to the method set(). If the key key does not exist in the dictionary, it is assigned a value by dict[key]=default.
dict.update(dict2)a Adds the key-value pairs of dictionary dict2 to dictionary dict
dict.values() returns a list containing all the values in the dictionary
①②③④⑤⑥⑦⑧⑨⑩
6. Set type
① Use set Factory methods set() and frozenset():
>>> s = set('cheeseshop')
>>> s
set(['c', 'e', 'h', ' o', 'p', 's'])
>>> t = frozenset('bookshop')
>>> t
frozenset(['b', 'h', 'k' , 'o', 'p', 's'])
>>> type(s)
>>> type(t)
②How to update a set
Use various built-in methods and operators to add and delete members of the set:
>>> s.add('z')
>>> ; s
set(['c', 'e', 'h', 'o', 'p', 's', 'z'])
>>> s.update('pypi')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y', 'z'])
>>> s.remove('z')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])
>>> s -= set('pypi')
>>> s
set(['c', 'e', 'h', ' o', 's'])
③Delete set
del s
④Membership (in, not in)
>>> s = set('cheeseshop')
>>> t = frozenset('bookshop')
>>> 'k' in s
False
>>> 'k' in t
True
>>> 'c' not in t
True
⑤Sets are equivalent/not equivalent
>>> s == t
False
>>> s != t
True
>>> u = frozenset(s)
>>> s == u
True
>>> set('posh') == set('shop')
True
⑥Difference complement/relative complement (-)
two The difference complement or relative complement of a set (s and t) refers to a set C. The elements in this set only belong to the set s, not to the set t. There is an equivalent method for the difference sign, difference().
>>> s - t
set(['c', 'e'])
Symmetric difference (^): The symmetric difference is the XOR of the set