Dictionaries
Dictionaries (dicts
) are used to store data in key-value pairs.
dog = {
"name": "Scooby",
"breed": "Great Dane",
"speaks": True
}
# Items are accessed by key
print(dog["name"]) # "Scooby"
# A dict is mutable, i.e. you can add more items
dog["total_movies"] = 13
Combining dicts and lists #
Lists can contain primitives (like strings), but also collections (like other lists, or dicts):
# Using a list to store a list of dogs
dogs = [
{
"name": "Milou",
"breed": "Fox Terrier"
},
{
"name": "Balto",
"breed": "Husky"
},
{
"name": "Snoopy",
"breed": "Beagle"
}
]
print(len(dogs)) # 3
print(dogs[0]["name"]) # Milou