Using dictionaries in Python

04.04.2020

Creating Dictionaries

Let's start with an example.

person = {
    "name": "Keith",
    "age": 28,
}

Here we create a variable names person as a dictionary type. We can tell the type in python from the brackets {}.

You can see inside the brackets we can set properties of the dictionary using a string as the key and any regular python type as the value.

One example property from the person variable above is name. Using python terminology, we have ""name" in quotes as the key and the value is another string "Keith".

You don't have to start with values in your dictionary. Let's look at create the same example above, but we can build the dictionary incrementally.

person = {}
person["name"] = "Keith"
person["age"] = 28

In this example, we started with an empty dictionary and added the properties later. Python allow for a lot of flexibility, and declaring values afterward in a dictionary is a great example of that flexibility.

Accessing Values

Accessing values is pretty straightforward, and we have already seen an example above. Let's continue using our person variable.

print(person["name"]) # prints Keith
print(person["age"]) # prints 28

That's it. We can use notation similar to arrays, but instead of passing in the index, we pass in the name of the property.

Looping over Dictionaries

For our last example, let's loop over the properties inside a dictionary. If you haven't learned loops yet, don't worry, you can come back later or just try the example for fun.

for key, value in person.items():
    print(key, value)

# Print outs
# name, Keith
# age, 28

Here we use a built in method called items(), then we use the for loop in python to iterate over the items in our dictionary.

This is a more advanced loop as we use something called destructuring to get two values at once. Don't worry about this too much. Just notice that we are saying, "Give me key, value from the person items, please".

Further Reading

If you would like to view more example, check out these resources!

Examples

  • @TODO: More examples coming soon!