Dict¶

Dictionary is the second most frequently used data structure in Python. Dictionary is an implementation of a hash table, therefore you cannot use a non-hashable object as a key, for example, a list (this is where a tuple might come in handy). A dictionary key can be any immutable object: a number, string, datetime, and even a function. Such objects have the __hash__() method, which uniquely maps an object to a certain number. The dictionary uses this number to look up the value for the key.

Lists, dictionaries, and sets (which we'll look at shortly) are mutable and don't have a hashing method; attempting to use them as dictionary keys will result in an error.

In [ ]:
d = {}  # Creating an empty dictionary

d: dict[str, str] = {"Italy": "Pizza", "US": "Hot-Dog", "China": "Dim Sum"}  # Filling the dictionary

k = ["Italy", "US", "China"]
v = ["Pizza", "Hot-Dog", "Dim Sum"]
d = dict(zip(k, v))  # Creating a dictionary from two collections using zip

k = d.keys()  # Collection of keys
v = d.values()  # Collection of values
k_v = d.items()  # Key-value tuples

print(d)
print(k)
print(v)
print(k_v)

print(f"Mapping: {k.mapping['Italy']}")

d.update({"China": "Dumplings"})  # Adding a value. If the key matches, the old value will be overwritten
print(f"Replace item: {d}")

c = d["China"]  # Reading a value
print(f"Read item: {c}")

try:
    v = d.pop("Spain")  # Deletes the value or raises a KeyError
except KeyError:
    print("Dictionary key doesn't exist")

# Examples of dict comprehension (comprehension will be discussed in more detail later)
b = {k: v for k, v in d.items() if "a" in k}  # Returns a new dictionary filtered by the key's value
print(b)

c = {k: v for k, v in d.items() if len(v) >= 7}  # Returns a new dictionary filtered by the length of the values
print(c)

d.clear() # Очистка словаря
{'Italy': 'Pizza', 'US': 'Hot-Dog', 'China': 'Dim Sum'}
dict_keys(['Italy', 'US', 'China'])
dict_values(['Pizza', 'Hot-Dog', 'Dim Sum'])
dict_items([('Italy', 'Pizza'), ('US', 'Hot-Dog'), ('China', 'Dim Sum')])
Mapping: Pizza
Replace item: {'Italy': 'Pizza', 'US': 'Hot-Dog', 'China': 'Dumplings'}
Read item: Dumplings
Dictionary key doesn't exist
{'Italy': 'Pizza', 'China': 'Dumplings'}
{'US': 'Hot-Dog', 'China': 'Dumplings'}

What can be a key in a dictionary?

A dictionary key can be any hashable object — a number, string, datetime, or even a function, i.e., objects that have a __hash__ method which uniquely maps the object to a certain number.