Table of Contents
A dictionary is a mutable data type that stores mappings of unique keys to values.
months= {“january”: 1, “february”: 2, “march”: 3}
Dictionaries are very useful because allow us to do fast database operations in Python
Dictionaries have different names in different languages, like:
- “Associative Arrays” in PHP/Pearl
- Properties or Map in Java
- Property Bag in C#
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, an 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 create a dictionary in Python?
months= {“january”: 1, “february”: 2, “march”: 3}
or
months = dict()
months[‘january’] = 1
months[‘february’] = 2
months[‘march’] = 3
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’])
//1
print(months[7])
//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
colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
print(colors.keys())
//dict_keys([‘red’, ‘blue’, ‘green’, ‘white’, ‘black’])
!!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])
How to get values from a dictionary?
values() returns a list of all the values available in a given dictionary.
colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
print(colors.values())
//dict_values([2, 3, 1, 1, 1])
How to get a sorted version of a dictionary?
We can use the ability to sort a list of tuples to get a sorted version of a dictionary!
>>> colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
>>> colors.items()
dict_items([(‘red’, 2), (‘blue’, 3), (‘green’, 1), (‘white’, 1), (‘black’, 1)])
then
>>> sorted(colors.items())
[(‘black’, 1), (‘blue’, 3), (‘green’, 1), (‘red’, 2), (‘white’, 1)]
Also we can write and compose this in a for loop as follows:
for k,v in sorted(colors.items()):
print(k, v)
How to sort by value instead of key?
colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
new_colors = list()for k,v in colors.items():
new_colors.append((v, k))new_colors = sorted(new_colors)
#new_colors = sorted(new_colors, reverse=True) # the reverse flag can be set to request the result in descending order
print(new_colors)//[(1, ‘black’), (1, ‘green’), (1, ‘white’), (2, ‘red’), (3, ‘blue’)]
or in a short way, using List Comprehensions as follows:
colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
print(sorted( [ (v, k) for k,v in colors.items()] ))
[(1, ‘black’), (1, ‘green’), (1, ‘white’), (2, ‘red’), (3, ‘blue’)]
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
items() method returns a view object that displays a list of dictionary’s (key, value) tuple pairs.
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 first variable is the key and the second variable is the corresponding value for the key.
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! Don’t expect the order of dictionaries to be a predictable thing.
Because dictionaries are not ordered, they are not sortable.
How are Python dictionaries different from Python lists?
Python lists maintain order and dictionaries do not maintain order
Dictionary Exercises
Count the words
counts = dict() words = ['red','blue','green','white','black', 'blue', 'blue', 'red'] for word in words: if word not in counts: counts[word] = 1 else: counts[word] += 1 print(counts) //{'red': 2, 'blue': 3, 'green': 1, 'white': 1, 'black': 1}
or we can use get() method and provide a default value of zero when the key is not in the words dictionary.
counts = dict() words = ['red','blue','green','white','black', 'blue', 'blue', 'red'] for word in words: counts[word] = counts.get(word, 0) + 1 print(counts) //{'red': 2, 'blue': 3, 'green': 1, 'white': 1, 'black': 1}
Hello there!
I hope you find this post useful!I'm Mihai, a programmer and 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!