Python advanced dictionary operation summary

  • 2020-05-17 05:43:38
  • OfStack

1. Calculations related to dictionary values

The problem

You want to calculate the value of the dictionary, such as finding the item with the largest (smallest) corresponding value in the dictionary.

Solution 1:

If you want to find the smallest item in the dictionary {'a':3, 'b':2, 'c':6}, you can do this:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min(zip(d.values(), d.keys()))
(2, 'b')

It is worth noting that d.values () gets all the values of the dictionary, d.keys() Gets all the keys of the dictionary, and the order of the two sequences remains 11. so zip(d.values() , d.keys()) Essentially, one (value, key) sequence is generated. The min function finds its minimum value by comparing tuples (value, key) in a sequence.

Solution 2:

In addition to using zip(d.values() ,  d.keys()) It can also be used dict.items() Method and generator derivation to generate (value, key) sequences, which are then passed to the min function for comparison:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')

Here is the argument to the min function (v ,k) for (k, v) in d.items() In fact, it is a generator derivation (like list derivation 1, only the [] of list derivation is changed to (), and it returns a generator instead of a list). Since the generator derivation is used as the parameter of min function, the parentheses on both sides can be omitted ((v ,k) for (k, v) in d.items()) ) .

2. Dictionary derivation

The problem

Want to convert a list of tuples into a dictionary, for example [('a', 1), ('b', 2), ('c', 3)] into {'a': 1, 'b': 2, 'c': 3}

The solution

Similar to the list derivation, dictionary derivation makes it easy to construct dictionaries from other data structures, such as:


>>> l = [('a', 1), ('b', 2), ('c', 3)]
>>> {k: v for k, v in l}
{'c': 3, 'b': 2, 'a': 1}

Dictionary derivation rules and list derivation 1, just replace [] with {}

3. Look for the intersection of dictionaries

The problem

Suppose there are two dictionaries:


d1 = {'a':1, 'b':2, 'c':3, 'd':4}
d2 = {'b':2, 'c':3, 'd':3, 'e':5}

To find the entries in the two dictionaries that have a common key, the result {'b':2, 'c':3}

The solution

We know that 1 goes through d.items() Method to traverse the dictionary, d.items() The object returned by the method is a class collection object, which supports the basic operations of the collection, such as fetch intersection, union and so on.


>>> dict(d1.items() & d2.items()) #  Take the intersection 
{'b': 2, 'c': 3}

In addition, d.keys() The key that returns the dictionary is also an object of class collection. If we only want to find the item with the same key in two dictionaries, we can do this:


>>> { k:d1[k] for k in d1.keys() & d2.keys() }
{'b': 2, 'd': 4, 'c': 3}

Here if the same key corresponds to a different value then you go to the value in the first dictionary. To generalize, if you want to exclude certain keys from the dictionary, you can do something like this:


>>> { k:d1[k] for k in d1.keys() - {'c', 'd'} } # -  Number means the difference set operation of a set 
{'b': 2, 'a': 1}

But one thing to note is, d.values() Returns the value of the dictionary. Since the value of the dictionary is not 1, it must be 1 d.values() One-like collection operations are not supported because one-like collection operations are generally not a set.

4. Connect multiple dictionaries into one dictionary

The problem

There are multiple dictionaries, such as:


d1 = {'a':1, 'b':2, 'c':3}
d2 = {'c':4, 'd':5, 'e':6}

You want to join these dictionaries into a single dictionary, or iterate through multiple dictionaries once.

The solution

use collections.ChainMap  :


>>> from collections import ChainMap

>>> chain_dict = ChainMap(d1, d2)
>>> for k, v in chain_dict.items():
    print(k, v)
a 1
e 6
d 5
c 3
b 2

ChainMap concatenates the incoming dictionaries into one dictionary and returns an ChainMap object, which ACTS like a single dictionary of one and can be evaluated or iterated. Notice here that the key c corresponds to a value of 3. If the dictionary passed into ChainMap contains the same key, the corresponding value is the value passed into the dictionary first.

In addition, if you want to simply iterate over the dictionary's key-value pairs, you can use them in combination items() and itertools.chain() Methods:


>>> from itertools import chain
>>> for k, v in chain(d1.items(), d2.items()):
  print(k, v)

a 1
c 3
b 2
e 6
c 4
d 5

Here the same keys are iterated separately.

5. Keep your dictionary in order

The problem

You want the order in which the elements in the dictionary are iterated and the order in which they are added to the dictionary to be 1

The solution

In general, use d.items() or d.keys() , d.values() The sequence of elements iterated through the method is unpredictable. For example, the dictionary d = {'a':1, 'b':2, 'c':3} Iterations:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')
0

The results may vary from run to run. If you want the order in which the elements are iterated to be the same as the order in which the dictionary was created, use collections.OrderedDict Instead of the regular dict:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')
1

OrderedDict actually records the order in which elements are added by maintaining a bidirectional linked list, so it consumes about twice as much memory as a normal dictionary. Therefore, various factors should be taken into consideration to decide whether to use OrderedDict in practice.

6. Map the dictionary keys to multiple values

The problem

Normally the dictionary keys correspond to only one value. Now you want one key for multiple values.

The solution

In order for a key to correspond to multiple values, you first need to put multiple values into a single container (such as a list or collection, etc.). For example, there is a list like this: [('a', 1), ('a', 2), ('b', 3), ('b', 4), ('c', 5)] , we will convert it into a dictionary to keep the corresponding relationship between the key and value of the element. Normally, we will write code like this:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')
2

but if else Statements make code a little redundant and unreadable, and Python's defaultdict improves that code.


>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in l:
  d[k].append(v)

>>> pprint(d)
defaultdict(<class 'list'>, {'c': [5], 'b': [3, 4], 'a': [1, 2]})

if else Is gone.

defaultdict is a subclass of dict. For dict, the dict[key] value operation throws an KeyError exception if key does not exist, but defaultdict returns either an instance of a class passed into the defaultdict constructor (such as a list) or a custom missing value. So in the example above, theta d[k].append(v) , when k does not exist, d[k] = [] is executed and the empty list is returned, then v is added to the list.

The value passed into the defualtdict constructor is either a class or a callable function. When the corresponding key is not in defualtdict, the default value is the return value of this function. For example:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')
4

With such a feature, we can construct the dictionary structure of infinite depth:


>>> d = {'a':3, 'b':2, 'c':6}
>>> min((v ,k) for (k, v) in d.items())
(2, 'b')
5

Here, when d['a'] is executed, 1 is returned because the corresponding key does not exist defaultdict(tree) , when executed again d['a']['b'] = 1 When, set the value corresponding to the key b to 1.

conclusion

The above is the whole content of this article, I hope the content of this article can help you to learn or use python, if you have any questions, you can leave a message to communicate.


Related articles: