Use defaultdict to initialize dictionaries and apply methods in Python

  • 2021-01-19 22:19:11
  • OfStack

In Python, you can use the defaultdict class implementation in collections to create a dictionary for unification initialization. Here are two common 1-point initializations, initialized to list and int.

Example code initialized as list:


#!/usr/bin/python
 
from collectionsimport defaultdict
 
s = [('yellow',1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d =defaultdict(list)
for k,v in s:
d[k].append(v)
print(d.items()

The running results are as follows:

E:\WorkSpace\05_ Data Analysis \01_ Using Python for Data Analysis \ Chapter 02 _ Introduction > pythondict_init.py


[('blue', [2, 4]),('red', [1]), ('yellow', [1, 3])]

As you can see from the above results, this initialization function is very suitable for counting the number of key occurrences. The second way to initialize int is different. Instead of counting all value's of key, it is appropriate to count how many times a single key has occurred.

The sample code is as follows:


from collectionsimport defaultdict
 
s = 'mississippi'
d =defaultdict(int)
for k in s:
d[k] += 1
print(d.items())

The running results are as follows:


E:\WorkSpace\05_ The data analysis \01_ using Python Conduct data analysis \ The first 02 chapter _ The introduction >pythondict_int_int.py
[('i', 4), ('p',2), ('s', 4), ('m', 1)]

In the above results, the key for each dictionary corresponds to the value for the number of occurrences.


Related articles: