Dictionaries and Special Dictionaries in Python

In Python, a dictionary (dict) is a built-in data structure used to store key-value pairs.

The keys in a dictionary must be unique and immutable (for example, strings, numbers, or tuples), while the values can be any type of object.

Example:

my_dict = {}my_dict['Zhang San'] = {'gender': 'male', 'age': 19}my_dict[1] = 'one'
# Output:
# {'Zhang San': {'gender': 'male', 'age': 19}, 1: 'one'}print(my_dict)
# Delete key-value pair
del my_dict['Zhang San']
# Output: {1: 'one'}print(my_dict)
# Access key-value pairs
# Output: key: 1, value: onefor key, value in my_dict.items():    print(f'key: {key}, value: {value}')

In addition to the built-in dictionary, the Python standard library’s collections module also provides several special dictionary types: defaultdict, OrderedDict, ChainMap, and Counter, each with different uses and characteristics.

defaultdict

defaultdict is a subclass of dict that can provide a default value for the keys in the dictionary,and it will not raise an exception when accessing a non-existent key.

Example:

from collections import defaultdict
# Default value of int type is 0my_dict = defaultdict(int)my_dict['a'] += 1my_dict['b'] = my_dict['a'] + 1my_dict['c'] = my_dict['b'] + 1
# Output: defaultdict(<class 'int'>, {'a': 1, 'b': 2, 'c': 3})print(my_dict)
# Output: 0print(my_dict['d'])

OrderedDict

OrderedDict is a subclass of dict,which stores the items based on the order of insertion.

In Python 3.7 and later, the regular dict also supports this feature by default.

Example:

from collections import OrderedDict
my_dict = OrderedDict()my_dict[3] = 'three'my_dict[2] = 'two'my_dict[1] = 'one'
# Output:
# OrderedDict([(3, 'three'), (2, 'two'), (1, 'one')])print(my_dict)

ChainMap

ChainMap is a class used tocombine multiple dictionaries, and when looking up a key in a ChainMap object, it willsearch through all dictionaries in order until the key is found.

from collections import ChainMap
dict1 = {'a': 1, 'b': 2}dict2 = {'b': 20, 'c': 30}chain_map = ChainMap(dict1, dict2)
# Output: 1 (from dict1)print(chain_map['a'])
# Output: 2 (from dict1, because 'b' in dict1 comes before 'b' in dict2)print(chain_map['b'])
# Output: 30 (from dict2)print(chain_map['c'])

Counter

Counter is a subclass of dict used tocount the occurrences of elements.

Example:

from collections import Counter
my_list = [1, 1, 2, 2, 2, 3]my_counter = Counter(my_list)
# Output: 2 (1 appears 2 times)print(my_counter[1])
# Output: 3 (2 appears 3 times)print(my_counter[2])
# Output: 1 (3 appears 1 time)print(my_counter[3])
my_str = 'hello world'my_counter = Counter(my_str)
# Output: 2 ('o' appears 2 times)print(my_counter['o'])

Leave a Comment