Summary of dict in python

Some summary of python about dict

Summarizes some tips or points to note about dictionaries.

create dictionary using zip

There are three ways to create a dictionary

dict(a=1, b=2, c=2)
dict([(a,1), (b,2), (c,3)])
dict({a:1, b:2, c:3})

It is recommended to use the second method combined with zip to create

key = 'abcde'
value = range(1, 6)
dict(zip(key, value))

Use iteritems to iterate over a dictionary

d = dict(a=1, b=2, c=3)
for k, v in d.iteritems():
    print k, v
# a 1
# c 3
# b 2

Of course, you can also use items to traverse the dictionary. The difference is that iteritems returns an iterator.

d = dict(a=1, b=2, c=3)
for k, v in d.items():
    print k, v
# a 1
# c 3
# b 2
In [69]: d.iteritems()
Out[69]: <dictionary-itemiterator at 0x3f216d8>

In [70]: d.items()
Out[70]: [('a', 1), ('c', 3), ('b', 2)]

Use get, pop to get/delete keys

First, dict[key] and delete dict[key] can also get/delete keys. But when the key does not exist, a KeyError exception will be raised. To avoid throwing exceptions you can use get and pop with defaut parameter

  • get(key[, default])
    If the key is in the dictionary, return the corresponding value, otherwise return default. So the exception is never thrown.
  • pop(key[, default])
    If default is not set, deleting the key will throw an exception if the key is not in the dictionary. Add default when using.

dict(dict1, **dict2) merges two dictionaries

To merge two dictionaries, you can first divide the two dictionaries into key-value pairs, and then connect the two key-value pairs to generate a new dictionary. ie dict(dict1.items()+dict2.items()). However, the efficiency is somewhat low. Concatenate
the two dictionaries using the more efficient .dict(dict1, **dict2)

In [29]: dict1
Out[29]: {'a': 1, 'b': 2, 'c': 3}

In [30]: dict2
Out[30]: {'d': 4, 'e': 5, 'f': 6}

In [31]: dict(dict1, **dict2)
Out[31]: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
$ python -m timeit -s 'dict1=dict2=dict(a=1,b=2)' 'dict3=dict(dict1,**dict2)'
1000000 loops, best of 3: 0.573 usec per loop
$ python -m timeit -s 'dict1=dict2=dict(a=1,b=2)' 'dict3=dict(dict1.items()+dict2.items())'
100000 loops, best of 3: 2.21 usec per loop

Use dict.copy() with caution

dict.copy() is a shallow copy. When encountering a dictionary or a list, it will not copy completely. Use the deepcopy() method of the copy module.

import copy

dict1 = {'a': [1, 2], 'b': 3}
dict2 = dict1
dict3 = dict1.copy()
dict4 = copy.deepcopy(dict1)

dict1['b'] = 'change'
dict1['a'].append('change')

print dict1  # {'a': [1, 2, 'change'], 'b': 'change'}
print dict2  # {'a': [1, 2, 'change'], 'b': 'change'}
print dict3  # {'a': [1, 2, 'change'], 'b': 3}
print dict4  # {'a': [1, 2], 'b': 3}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325380642&siteId=291194637