Dictionaries in Python ✅ Exercises and examples

Dictionaries in Python

A dictionary is a mutable data type that stores mappings of unique keys to values.

months= {“january”: 1, “february”: 2, “march”: 3}

Dictionaries can have keys of any immutable type, like integers, floats, strings or tuples. They must be of a type that is not modifiable!

In Python, any immutable object is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values. This is why Python requires us to use immutable datatypes for the keys in a dictionary.

Also, It’s not even necessary for every key to have the same type!

months= {“january”: 1, “february”: 2, “march”: 3, 7: ‘seven’}

How to insert values in a dictionary?

You can insert new values in a dictionary using square brackets that enclose the key.

months['april']=4
print(months)

# {'january': 1, 'february': 2, 'march': 3, 7: 'seven', 'april': 4}

How to look up values in a dictionary?

You can look up values in a dictionary using square brackets that enclose the key.

months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
print(months['january'])
print(months[7])

# 1
# seven

If the key is not present in the dictionary, You will get a KeyError!

months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
print(months['april'])

#KeyError: 'april'

To prevent this you can use get() method.

Dictionary methods

get() method

Get looks up values in a dictionary, but unlike square brackets, get returns None if the key isn’t found.

months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
print(months.get('april'))

# None

If you expect lookups to sometimes fail, get() might be better to use than normal square bracket lookups.

How to check if a value is in a dictionary?

You can check whether a value is in a dictionary the same way You check whether a value is in a list or set with the in keyword.

months = {'january': 1, 'february': 2, 'march': 3, 7: 'seven', 'april': 4}
print("june" in months)

# False
months = {'january': 1, 'february': 2, 'march': 3, 7: 'seven', 'april': 4}
print("january" in months)

# True

How to check if a key return None?

You can check if a key returned None using Identity Operator
Check if is None with the is operator. Also, You can check for the opposite using is not operator.

months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
find_month = months.get('april')
print(find_month is None)

# True
months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
find_month = months.get('april')
print(find_month is not None)

# False

How to get dictionary keys as a list?

Using keys() method

!!Be careful! In Python 2, dict.keys() returns a list while in Python 3 dict.keys() returns an iterable object, not a list-like object! So if You try to sort dict.keys().sort() in Python 3 will get this error: AttributeError: ‘dict_keys’ object has no attribute ‘sort’. To avoid this error, In Python3 you can use sorted() function

months= {"january": 1, "february": 2, "march": 3, 7: 'seven'}
print(months.keys())

# dict_keys(['january', 'february', 'march', 7])

You can also use a list comprehension:

sorted_keys = [k  for  k in  dict.keys()]
sorted_keys.sort()
print(sorted_keys)

How to create and sort a list of the dictionary’s keys?

sorted_keys = sorted(dict.keys())

How to get the first element in the sorted list of keys?

print(sorted_keys[0])

How to find the element with the highest value in the list of keys?

print(sorted_keys[-1])

Compound Data Structures

You can include dictionaries in other dictionaries to create compound data structures, e.g:

months = {"january": {"Wednesday": 1,
                      "thursday": 2,
                      "friday": 3},
          "february": {"saturday": 1,
                       "sunday": 2,
                       "monday": 3
          }
}
print(months)

# {'january': {'Wednesday': 1, 'thursday': 2, 'friday': 3}, 'february': {'saturday': 1, 'sunday': 2, 'monday': 3}}

Access elements in a nested dictionary

months = {"january": {"wednesday": 1,
                      "thursday": 2,
                      "friday": 3},
          "february": {"saturday": 1,
                       "sunday": 2,
                       "monday": 3
          }
}
print(months["january"])
# {'wednesday': 1, 'thursday': 2, 'friday': 3}
print(months["january"]["thursday"])
# 2

Iterating Through Dictionaries with For Loops

Iterating through it in the usual way with a for loop would give you just the keys:

for color in colors:
    print(color)

# red
blue
green
white
black

To iterate through both keys and values, you can use the built-in method items() like this:

colors = {
    "red": 1,
    "blue": 2,
    "green": 3,
    "white": 4,
    "black": 5
}

for key, value in colors.items():
    print("Color: {} - Value: {}".format(key, value))

# Color: red - Value: 1
Color: blue - Value: 2
Color: green - Value: 3
Color: white - Value: 4
Color: black - Value: 5

The items() method returns a view object that displays a list of dictionary’s (key, value) tuple pairs.

Conclusions about Dinctionaries in Python

  • A dictionary is a mutable data structure.
  • A dictionary can be indexed using keys.
  • The keys of a dictionary are unique and must to be immutable.
  • The items in a dictionary are not ordered! Because dictionaries are not ordered, they are not sortable.

Hello there!

I hope you find this post useful!

I'm Mihai, an online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Reply

Your email address will not be published. Required fields are marked *