Calculations related to dictionary values
Problem
You want to calculate the value of a dictionary, for example, to find the item with the largest (smallest) corresponding value in the dictionary.
Solution One:
Suppose you want to find the item with the smallest value from the dictionary {' A ': 3, ' B ': 2, ' C ': 6}:
>>> d = {' A ': 3, ' B ': 2, ' C ': 6}
>>> min (Zip (d.values (), D.keys ()))
(2, ' B '))
It is noteworthy that d.values () gets the full value of the dictionary, d.keys()
gets all the keys to the dictionary, and the Order of the two sequences remains one by one corresponding. So zip(d.values() , d.keys())
essentially a sequence of (value, key) is generated. The Min function finds its smallest value by comparing the tuples (value, key) in the sequence.
Solution Two:
In addition to zip(d.values() , d.keys())
being used, dict.items()
methods and generator derivations can be used to generate (value, key) sequences, which are 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 the Min function's argument (v ,k) for (k, v) in d.items()
is actually a generator derivation (as with list derivation, just to change the [] of the list derivation to (), and it returns a generator instead of a list), because the generator is deduced as the parameter of the Min function, So you can omit both sides of the brackets (not as a parameter when the writing should be ((v ,k) for (k, v) in d.items()) )
.)
Second, the dictionary derivation type
Problem
Want to convert a list of tuples into a dictionary, such as translating [('a', 1), ('b', 2), ('c', 3)]
{'a': 1, 'b': 2, 'c': 3}
Solution
Similar to list derivations, dictionary derivations can easily 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-derived rules and list derivation, just replace [] with {}
Finding the intersection of dictionaries
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 items in these two dictionaries that have a common key, that is to get the result {' B ': 2, ' C ': 3}
Solution
We know that generally through the d.items()
method to traverse the dictionary, the d.items()
method returned object is a class collection object, support the basic operation of the set, such as intersection, and set.
>>> Dict (D1.items () & D2.items ()) # take intersection
{' B ': 2, ' C ': 3}
In addition, d.keys()
returning the dictionary key is also a class collection object, and if we only want to find items with the same key in two dictionaries, you 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, go to the value in the first dictionary. To generalize, if you want to exclude some of the keys in the dictionary, you can do this:
>>> {K:d1[k] for K in D1.keys ()-{' C ', ' d '}} #-number meaning is the set's difference operation
{' B ': 2, ' A ': 1}
It is important to note, however, that the value of the d.values()
dictionary is returned, and because the dictionary corresponds to a value that is not necessarily unique, it is not d.values()
generally possible to form a collection and therefore does not support general collection operations.
Four or more dictionaries connected into a dictionary
Problem
There are multiple dictionaries, for example:
D1 = {' A ': 1, ' B ': 2, ' C ': 3}
d2 = {' C ': 4, ' d ': 5, ' E ': 6}
You want to connect these dictionaries to a single dictionary, or to iterate over multiple dictionaries at once.
Solution
Use collections.ChainMap
:
>>> from collections import Chainmap
>>> chain_dict = chainmap (d1, D2)
>>> for K, v I n Chain_dict.items ():
print (k, v)
a 1
e 6
d 5
c 3
B 2
Chainmap joins more than one dictionary into a dictionary and returns a Chainmap object that behaves like a single dictionary, and can be evaluated or iterated. Note that the value of the key C corresponds to 3, and if the incoming Chainmap dictionary contains the same key, the corresponding value is the value in the dictionary that is passed in first.
In addition, if you want to simply iterate through the dictionary's key-value pairs, you can combine the use items()
and the itertools.chain()
method:
>>> from itertools import chain
>>> to 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.
V. Keep the dictionary in order
Problem
Want to keep the iteration order of the elements in the dictionary consistent with the order in which they are added to the dictionary
Solution
In general, the d.items()
order of elements that are used or d.keys()
d.values()
iterated by methods is unpredictable. For example, for dictionary d = {'a':1, 'b':2, 'c':3}
iterations:
>>> d = dict ()
>>> d[' a '] = 1
>>> d[' b '] = 2
>>> d[' c '] = 3
>&G T;> for K, v. in D.items ():
print (k, v)
a 1
c 3
B 2
Each run can be a different result. If you want the sequence of element iterations to be the same as the order of the elements when you create the dictionary, you'll use collections.OrderedDict
the dict instead of the normal:
>>> from collections import ordereddict
>>> ordered_d = ordereddict ()
>>> ordered_d [' a '] = 1
>>> ordered_d[' b '] = 2
>>> ordered_d[' c '] = 3
>>> for K, V in ORDERED_D.I TEMs ():
print (k, v)
a 1
B 2
c 3
Ordereddict actually records the order of elements added by maintaining a two-way list, so it consumes about twice times as much memory as the average dictionary. Therefore, in the actual use of the need to consider a variety of factors to determine whether to use Ordereddict.
To make the key of the dictionary map multiple values
Problem
In general, the key of the dictionary corresponds to only one value. Now you want to have a key that corresponds to multiple values.
Solution
In order for a key to correspond to multiple values, you first need to place multiple values in a container (such as a list or a collection, and so on). For example, there is a list: [('a', 1), ('a', 2), ('b', 3), ('b', 4), ('c', 5)]
We're going to convert it into a dictionary, keep the key-value correspondence of the elements, and we usually write code like this:
>>> from pprint import pprint
>>> l = [(' A ', 1], (' A ', 2), (' B ', 3), (' B ', 4), (' C ', 5)]
>> ;> d = {}
>>> for K, v. in L:
if k in D:
d[k].append (v)
else:
d[k] = [v]
>>> p Print (d)
{' A ': [1, 2], ' B ': [3, 4], ' C ': [5]}
But if else
the statement makes the code appear somewhat redundant and unreadable, and Python's defaultdict improves the code.
>>> from collections import Defaultdict
>>> d = defaultdict (list)
>>> for K, V in l:< C14/>d[k].append (v)
>>> Pprint (d)
defaultdict (<class ' list ', {' C ': [5], ' B ': [3, 4], ' a ': [1, 2]})
if else
The sentence is gone.
Defaultdict is a subclass of Dict. For Dict, a Dict[key value operation throws a Keyerror exception if the key does not exist, but Defaultdict returns an instance of the class that passed in the Defaultdict constructor, such as a list, or a custom missing value. So in the above example, for d[k].append(v)
, when K does not exist, it executes d[k] = [] and returns the empty list, which then joins v into the list.
The value passed into the Defualtdict constructor is not necessarily a class, it can also be a callable function, and when the corresponding key is not in the defualtdict, its default value is the return value of the function, for example:
>>> from collections import defaultdict
>>> def zero_default (): return
0
>>> d = Defaultdict (zero_default)
>>> d[' a '] = 1
>>> d[' A ']
1
>>> d[' B ']
0
>>> D.keys ()
Dict_keys ([' B ', ' a '])
>>>
With such a feature, we can construct a dictionary structure with infinite depth:
>>> from collections import defaultdict
>>> import json
>>> tree = lambda: Defaultdict (tree)
>>> d = tree ()
>>> d[' A ' [' b '] = 1
>>> print (json.dumps D ) # In order to display the format better see
{"a": {"B": 1}}
Here when executing d[' a ', the corresponding key does not exist, so it returns one defaultdict(tree)
, and when executed d['a']['b'] = 1
, the value of key B is set to 1.
Summarize
The above is the entire content of this article, I hope the content of this article for you to learn or use Python can have some help, if you have questions you can message exchange.