Summary of Python dictionary operations

  • 2020-05-09 18:45:14
  • OfStack

1.dict() create the dictionary


>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}

2.fromkeys() to create a "default" dictionary with the same values for the elements

>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}

3. Walk through the dictionary
Traverse using keys()

>>> 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

Iterate through using an iterator

>>> 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. Get the value value

The dictionary key is given in brackets


>>> dict2['name']
'earth'

5. Member operator :in or not in
Determine if the key exists

>>> 'server' in dict2 # or dict2.has_key('server')
False

6. Update your dictionary

>>> dict2['name'] = 'venus' # Update existing entries
>>> dict2['port'] = 6969 # Update existing entries
>>> dict2['arch'] = 'sunos5'# Add new entries

7. Delete the dictionary

del dict2['name']    ​# Delete key is" name The entry"
dict2.clear()    ​# delete dict2 All the entries in
del dict2     ​# Delete the entire dict2 The dictionary
dict2.pop('name')    ​# Delete and return key is" name The entry"

8.values() returns the list of values  

>>>
>>> dict2.values()
[80, 'earth']

9.items() returns the list of (key, value) tuples,  

>>> dict2.items()
[('port', 80), ('name', 'earth')]


Related articles: