Python #10: Dictionaries

Dictionaries are used as containers for pairs of values, which are called ‘key-value’ pairs. Like a regular dictionary, you got a word and its definition. With Python dictionaries, the word is the key and the definition is the value.

ages = {
    "Alice": 25,
    "Bob": 30,
    "Eve": 42
}

This code shows a dictionary called ‘ages’. So the names would be the keys and the numbers would be the values.

We use a dictionary by looking up a key to find its corresponding value.

ages = {
    "Alice": 25,
    "Bob": 30,
    "Eve": 42
}
print(ages["Alice"])

Output: 25

Just print the dictionary name and call the key with square brackets.

The industry term for connecting a key to a value is that they’re ‘mapped‘. In the past code, the name was mapped to the age number.

Looping over a dictionary works the same way as it does for lists and tuples. Use the ‘for’ and ‘in’ keywords

ages = {
    "Alice": 25,
    "Bob": 30,
    "Eve": 42
}

for name in ages:
    print(name)

Output: Alice Bob Eve

There may be cases where it outputs the keys out of order, but it’ll still show them.

If you want to extract the values instead of the keys, you’ll have to do an extra line.

ages = {
    "Alice": 25,
    "Bob": 30,
    "Eve": 42
}

for name in ages:
    age = ages[name]
    print(age)

Output: 25  30  42

Indent under the loop we just did, call a name for the value under the dictionary (in this case that’s ‘age’ of the ‘ages’), then print that value name.

Or to try that again, to extract a value from a key, you print the dictionary name, along with your selected key in square brackets.

moods = {
    "Alice": "happy",
    "Eve": "driven"
}

print(moods["Eve"])

Output: driven

Insert

To insert a key/value into a dictionary, you simply call the dictionary name, use square brackets to call the key, then equal that to the value you want to add. This also goes for changing a key’s value, you’re just overriding it in that case.

Checking

You can check for a key by using the ‘if’ and ‘in’ keywords. if “key name” in “dictionary name”. What you do with that is your choice, but it’s usually print or return.

Checking the length of a dictionary still uses the ‘len’ function. Just know it’ll only list how many key/value are in the dictionary, not total characters like it does for the others. Our age dictionary with 3 names and 3 ages would have a length of 3.

Leave a comment