Dictionaries (Cheat Sheet)

Dictionaries (Cheat Sheet)

Dictionaries are data structures which map keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed like lists, using square brackets containing keys.

Examples

speed = {"Mercedes": 200, "BMW": 210, "Volkswagen": 220}
print(speed["Mercedes"])
print(speed["Volkswagen"])

and empty dictionary

dic = {}

Important: keys have to be immutable

Searching for keys

Examples

print("Mercedes" in speed)
print("Airbus" not in speed)

Function get()

Get a value with the get function:

print(speed.get("BMW")

Return a default value if the key does not exist:

print(speed.get("Fiat":250)

 

Stefan Schneider Tue, 05/03/2022 - 17:03