Dictionaries are a special kind of data structure. When we used lists, each item in a list had an index, a number that represented its position in the list. For example, look at the following list:

cats = ["tabby", "tortoiseshell", "calico", "Siamese"]

To access calico, we’d type cats[2]. We say that lists are ordered—the position of an item in the list matters.

Dictionaries, on the other hand, are unordered. Instead of accessing items using an index, each item—a value—has a corresponding key that is used to access it. For example:

pets = {"Jay": "tortoise", "McKenna": "bearded dragon",
        "Oliver": "Siamese cat", "Lily": "hedgehog"}

"Jay" is a key and "tortoise" is the corresponding value. Notice that we use squiggly brackets {} to enclose a list, a colon : between a key and its value, and a comma , between items.

Above, we mentioned that dictionaries can have any data type as their keys or values. However, this can make interacting with those dictionaries a little more complicated.

Let's look at the pets dictionary from before.

What happens when you run a for loop to print the values?

We need a conditional to print differently depending on the data type. We'll use the type() function, which returns the data type of the variable or value fed to it.

for pet in pets.values():
 if type(pet) == str:
 print(pet)
 elif type(pet) == list:
 for item in pet:
 print(item)
 else:
 print("[Unknown data type]")

The else condition above catches any exceptions, so that if a value isn't a string or list, we don't get an error message.