Home >Backend Development >Python Tutorial >Defaultdict vs. Regular Dictionary: When and Why Use `int` and `list` Parameters?

Defaultdict vs. Regular Dictionary: When and Why Use `int` and `list` Parameters?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 21:19:12208browse

Defaultdict vs. Regular Dictionary: When and Why Use `int` and `list` Parameters?

defaultdict vs. Regular Dictionary

Despite reviewing the Python documentation's examples, clarifying the subtleties of the defaultdict method remains elusive. Let's explore these examples further and decipher the purpose of int and list parameters.

In the first example:

from collections import defaultdict
s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1

The defaultdict creates a mapping where each character in the string s maps to an integer. The int parameter indicates that when a new character is encountered in the string, the default value it takes on is 0. This is seen in the output:

d.items()
# dict_items([('m', 1), ('i', 4), ('s', 4), ('p', 2)])

In the second example:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

The defaultdict creates a mapping where each key (which is a color) maps to a list. The list parameter indicates that when a new color is encountered, the default value it takes on is an empty list. This is seen in the output:

d.items()
# [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Therefore, the int and list parameters in defaultdict specify the type of default object that is created when a new key is accessed. In the first example, new characters in the string map to 0, and in the second example, new colors map to empty lists.

The above is the detailed content of Defaultdict vs. Regular Dictionary: When and Why Use `int` and `list` Parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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