Dictionaries

Dictionaries consist of key-value pairs. Keys must be of invariant type, including numbers, Strings and Tuples.

Warning

Even if you can use different key types in a dictionary, you should avoid doing so, as this not only makes it more difficult to read, but also to sort.

Values can be any type of object, including mutable types such as Lists and Dictionaries.

>>> timeseries = {
...     "2022-01-31": -0.751442,
...     "2022-02-01": 0.816935,
...     "2022-02-02": -0.272546,
... }
>>> timeseries["2022-02-03"] = -0.268295

If you try to access the value of a key that is not contained in the dictionary, a KeyError Exceptions is thrown. To avoid this error, the dictionary method get optionally returns a user-defined value if a key is not contained in a dictionary.

>>> timeseries["2022-02-03"]
-0.268295
>>> timeseries["2022-02-04"]
Traceback (most recent call last):
  File "<python-input-15>", line 1, in <module>
    timeseries["2022-02-04"]
    ~~~~^^^^^^^^^^^^^^
KeyError: '2022-02-04'
>>> timeseries.get("2022-02-03", "Messwert nicht vorhanden")
-0.268295
>>> timeseries.get("2022-02-04", "Messwert nicht vorhanden")
'Messwert nicht vorhanden'

Other Dict methods

The len() function built into Dicts returns the number of key-value pairs. The del statement can be used to delete a key-value pair. As with Lists, several dictionary methods ((clear, copy, get, items, keys, update and values) are available.

The keys, values and items methods do not return lists, but dictionary view objects that behave like sequences, but are updated dynamically when the dictionary changes. For this reason, you must use the list() function so that they become a list in these examples:

>>> list(timeseries.keys())
['2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03']

As of Python 3.6, dictionaries retain the order in which the keys were created, and they are also returned in this order with keys.

Merging dictionaries

You can use the dict.update() method to merge two dictionaries into a single dictionary:

>>> titles = {7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}
>>> new_titles = {7.0: "Data types", 7.3: "Sets"}
>>> titles.update(new_titles)
>>> titles
{7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}

Note

The order of the operands is important, as 7.0 is duplicated and the value of the last key overwrites the previous one.

setdefault

setdefault can be used to provide counters for the keys of a dict, for example:

>>> titles = ["Data types", "Lists", "Sets", "Lists"]
>>> for title in titles:
...     titles_count.setdefault(title, 0)
...     titles_count[title] += 1
...
>>> titles_count
{'Data types': 1, 'Lists': 2, 'Sets': 1}

Note

Such counting operations quickly became widespread, so the collections.Counter class was later added to the Python standard library. This class can perform the above-mentioned operations much more easily:

>>> collections.Counter(titles)
Counter({'Lists': 2, 'Data types': 1, 'Sets': 1})

frozendict

Added in version 3.15: PEP 814 introduces frozendict, an immutable dictionary:

>>> titles = frozendict({7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"})
>>> titles
frozendict({7.0: 'Data Types', 7.1: 'Lists', 7.2: 'Tuples'})
>>> titles[7.3] = "Sets"
Traceback (most recent call last):
  File "<python-input-16>", line 1, in <module>
    titles[7.3] = "Sets"
    ~~~~~~^^^^^
TypeError: 'frozendict' object does not support item assignment

Immutable mappings are hashable, which means they can be used as keys in dictionaries, as elements in sets, or accepted as arguments by functions decorated with @functools.lru_cache():

>>> hash(titles)
3827265406416199624

The merge operator (|) can be used to merge two frozendict objects or a frozendict object with a dict object, for example:

>>> titles | new_titles
frozendict({7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'})

Extensions

python-benedict

dict subclass with keylist/keypath/keyattr support and I/O shortcuts.

pandas

can convert dicts into series and DataFrames.

Checks

  • Suppose you have the two dictionaries x = {"a": 1, "b": 2, "c": 3, "d": 4} and y = {"a": 5, "e": 6, "f": 7}. What would be the content of x after the following code snippets have been executed?

    >>> del x["b"]
    >>> z = x.setdefault("e", 8)
    >>> x.update(y)
    
  • Which of the following expressions can be a key of a dictionary? 1; "Veit"; ("Veit", [1]); [("Veit", [1])]; ["Veit"]; ("Veit", "Tim", "Monique")

  • You can use a dictionary and use it like a spreadsheet by using tuples as key row and column values. Write sample code to add and retrieve values.

  • How can you remove all duplicates from a list without changing the order of the elements in the list?