Home > Backend Development > Python Tutorial > Introduction to the usage of defaultdict type in Python's collections module

Introduction to the usage of defaultdict type in Python's collections module

WBOY
Release: 2016-07-22 08:56:29
Original
1848 people have browsed it

defaultdict is mainly used when value needs to be initialized. For a dictionary, the key must be hashable, immutable, and unique data, and the value can be any data type. If value is a data type such as list, dict, etc., it must be initialized to empty before use. In some cases, value needs to be initialized to a special value, such as 0 or ''.

from collections import defaultdict

person_by_age = defaultdict(list)
for person in persons:
  d[person.age].append(person.name)

Copy after login

defaultdict is used in the same way as dict, except that a callable object x must be passed in during initialization. When a key that does not exist yet is accessed, the value will be automatically set to x(). For example, in the above example, when a person of a certain age d[person.age] is accessed for the first time, it will become list(), that is, [].

Of course, you can also use your own defined callable object, such as:

d = defaultdict(lambda: 0)
d["hello"] += 1     # 1
d["a"]         # 0
Copy after login

defaultdict is more efficient than dict.set_default, and is more intuitive and convenient to use.

The standard dictionary includes a method setdefault() to get a value and create a default value if the value does not exist. defaultdict initializes the container to allow the caller to specify the default value in advance.

import collections
def default_factory():
  return 'default value'
d = collections.defaultdict(default_factory, foo = 'bar')
print 'd:', d
print 'foo =>', d['foo']
print 'var =>', d['bar']
Copy after login

This method can be used as long as all keys have the same default value.
The result above is:

d: defaultdict(<function default_factory at 0x0201FAB0>, {'foo': 'bar'})
foo => bar
var => default value
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template