“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

One-key multi-value dictionary

In Python programs, you can create dictionaries that map a key to multiple values, called multidict dictionaries.

Specific operation:

To make it easy to create dictionaries that map multiple values, you can use the defaultdict() function in the built-in module Collections. (One of the main features of this function is that it can instantiate a value as the default if the key is not present, which means that we only need to worry about adding elements when we use this function to create dictionaries.)

For example, the following dictionaries D and e are two typical one-key multi-value dictionaries, so how to implement defaultdict() function? d = {'a': [1.2.3],
}

e = {
    'a': {1.2.3}},Copy the code

The code:

from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(3)
print(d)
print(d['a'])		The lookup operation in the dictionary is the same as in the first lesson.


d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['a'].add(3)
print(d)
Copy the code

However, we use the function defaultdict() to automatically create dictionary entries for later use. If you don’t want this function, the teacher now teaches you a new method:Instead of using defaultdict(), we can call setdefault() on a normal dictionary.

The code:

d = {}
d.setdefault('a', []).append(1)
d.setdefault('a', []).append(2)
d.setdefault('b', []).append(3)
print(d)
Copy the code

Knowledge depot:

dict =defaultdict( factory_function)		# defaultdict takes a factory function as an argumentThis factory_function can be a list, STR,setIf a dictionary key is not present but is searched, the return is not keyError, but a default value (the default value of the factory function). The default value is: list corresponds to [], STR corresponds to an empty string,setThe correspondingset(), int corresponds0, from collections import defaultdict dict1 = defaultdict(int) dict2 = dict2 (set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] = 'nice'		# Nothing increases!

The dict1 dictionary key is 2 corresponding to value.
print(dict1[2])

Defaultdict (); defaultdict();
This key does not exist in any of the four dictionaries, so return the default value.
print(dict1[1])		
print(dict2[1])
print(dict3[1])
print(dict4[1])

# output:
nice
0
set()

[]
Copy the code
Knowledge depot upgrade: In addition to accepting the type name as an argument to the initialization function, this function can also use any callable function with no arguments, and then return the value of the function as the default value, making the default value more flexible. From collections import defaultdict def zero() here is an example of how to initialize a custom function with zero() as an argument:return 0
dict = defaultdict(zero)
print(dict)

print(dict['first'])

print(dict)
Copy the code

🔆 In The End!

Start now, stick to it, a little progress a day, in the near future, you will thank you for your efforts!

This blogger will continue to update the basic column of crawler and crawler combat column, carefully read this article friends, you can like the collection and comment on your feelings after reading. And can follow this blogger, read more crawler in the days ahead!

If there are mistakes or inappropriate words can be pointed out in the comment area, thank you! If reprint this article please contact me for my consent, and mark the source and the name of the blogger, thank you!