This article mainly introduces a concise summary of Python dictionary operations. This article summarizes creating a dictionary, creating a default dictionary, traversing a dictionary, obtaining value values, and member operators: frequently used operations such as in or notin, update dictionary, and delete Dictionary. For more information, see
1. dict () create a dictionary
The code is as follows:
>>> Fdict = dict (['X', 1], ['y', 2])
>>> Fdict
{'Y': 2, 'x': 1}
2. fromkeys () to create a "default" Dictionary. the elements in the dictionary have the same value.
The code is as follows:
>>> Ddict ={}. fromkeys ('X', 'y'),-1)
>>> Ddict
{'Y':-1, 'x':-1}
3. traverse the dictionary
Use keys () to traverse
The code is as follows:
>>> 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
Use iterator traversal
The code is as follows:
>>> 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
4. obtain the value
The dictionary key is enclosed in brackets.
The code is as follows:
>>> Dict2 ['name']
'Global'
5. member operators: in or not in
Determine whether a key exists
The code is as follows:
>>> 'Server' in dict2 # or dict2.has _ key ('server ')
False
6. update the dictionary
The code is as follows:
>>> Dict2 ['name'] = 'Venus' # update an existing entry
>>> Dict2 ['port'] = 6969 # update an existing entry
>>> Dict2 ['arch '] = 'sunos5' # Add a new entry
7. delete a dictionary
The code is as follows:
Del dict2 ['name'] # Delete an entry whose key is "name"
Dict2.clear () # Delete all entries in dict2
Del dict2 # delete the entire dict2 Dictionary
Dict2.pop ('name') # Delete and return an entry whose key is "name"
8. values () return value list
The code is as follows:
>>>
>>> Dict2.values ()
[80, 'global']
9. items () returns the list of (key, value) tuples
The code is as follows:
>>> Dict2.items ()
[('Port', 80), ('name', 'global')]