DICTIONARIES


Skip to a subsection :

  1. DIVE INTO THE DICTIONARIES
  2. WORKING WITH DICTIONARIES
  3. METHODS
  4. DICTIONARY COMPREHENSION
  5. MORE EXAMPLES



1. DIVE INTO THE DICTIONARIES

A python dictionary is a collection of key-value pairs. The keys are used to access the values, and the values can be any data type (such as a string, integer, or list).

Ordered

Starting from Python 3.7, dictionaries are ordered, which means that the items are stored in a specific order. dictionaries were unordered in Python v3.6 and earlier.

Mutable

They are also mutable, which means that you can add, remove, or modify the elements of a dictionary.

No duplicate

dictionaries do not allow duplicate keys. If you try to add a new key-value pair to a dictionary and the key already exists, the value for that key will be updated to the new value.

Syntax

Dictionaries are defined using curly braces {} . The key and value are separated by a colon.

Utilizing dictionaries

Dictionaries are best used when you need to store data as key-value pairs and you want to be able to quickly retrieve the value for a given key. Lookups are very efficient.

2. WORKING WITH DICTIONARIES

dictionaries are defined using curly braces ({ and }), with the key-value pairs separated by commas (,). The keys and values within each pair are separated by a colon (:). Here is a way to create a dictionary named 'myDict'

myDict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(myDict) # prints {'name': 'John', 'age': 30, 'city': 'New York'}

Dictionaries can be used to represent rows in a table, with each key representing a column in the table and the corresponding value representing the value in that column for a particular row. For example, consider a table of information about countries, with columns for the country name, capital, official language, and population. We can represent each row in this table as a dictionary, where the keys are the column names and the values are the corresponding data for each country. Using dictionaries in this way can be very useful for organizing and manipulating data. For example, we can easily access and modify the values for a particular country by referencing the dictionary for that country and the key for the desired value. We can also easily loop over all of the dictionaries in a list and perform operations on them, such as calculating statistics or generating reports.

China = {"Capital": "Beijing", "Currency": "Renminbi"}
Japan = {"Capital": "Tokyo", "Currency": "Yen"}
Korea = {"Capital": "Seoul", "Currency": "Won"}

Use the square brackets [] to access the value of a key in a dictionary. For example:

myDict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(myDict['name']) # prints John
print(myDict['age']) # prints 30
print(myDict['city']) # prints New York

You can use the 'in' operator to check if a key exists in a dictionary.

myDict = {'name': 'John', 'age': 30, 'city': 'New York'}
if 'name' in myDict:
print('name is in myDict') # prints name is in myDict

You can add an element to a dictionary without using a method by simply assigning a new key-value pair like this :

d = {'a': 1, 'b': 2}
d['c'] = 1
print(d) # prints {'a': 1, 'b': 2, 'c': 1}

3. METHODS

The methods for working with dictionaries can be categorized into the following groups:

These categories are not official and there may be other ways to categorize the methods. The goal of these categories is simply to provide a helpful overview and a way to better understand and organize the many tools available.


MODIFICATION METHODS

update(): updates a dictionary. Can be used to update the values of existing keys in a dictionary, or to add new key-value pairs to the dictionary if the keys do not already exist. In the example below, we will include the new entries for Chile and Argentina, and then print out the updated dictionary:

capitals={'Bolivia':'LaPaz','Colombia':'Bogota'}
more_capitals = {'Chile': 'Santiago', 'Argentina': 'Buenos Aires'}
capitals.update(more_capitals) 
print(capitals) # prints {'Bolivia': 'LaPaz', 'Colombia': 'Bogota', 'Chile': 'Santiago', 'Argentina': 'Buenos Aires'}

clear(): removes all the elements from the dictionary

myDict = {'a': 12, 'b': 2, 'c': 3}
myDict.clear()
print(myDict) # prints {}

pop(): removes the specified key and returns its value, or a default value if the key is not found

myDict = {'a': 12, 'b': 2, 'c': 3}
print(myDict.pop('a')) # prints 12
print(myDict) # prints {'b': 2, 'c': 3}

popitem(): removes and returns an arbitrary key-value pair from the dictionary. The key-value pair that is removed from the dictionary is chosen randomly, rather than being specified by the user.

myDict = {'a': 12, 'b': 2, 'c': 3}
print(myDict.popitem()) # prints ('c', 3)
print(myDict) # prints {'a': 12, 'b': 2}

setdefault(): returns the value for the specified key, or sets a default value if the key is not found. In the example below, setdefault() method returns the value of key 'a'. As the key exists in the dictionary, it simply retrieves the value for the key and return it, without modifying the dictionary

myDict = {'a': 12, 'b': 2, 'c': 3}
print(myDict.setdefault('a')) # prints 12
print(myDict) # prints {'a': 12, 'b': 2, 'c': 3}

In this different example, setdefault() method adds the 'd':5 key-value pair because 'd' is not found in the keys. It modifies the diction

myDict = {'a': 12, 'b': 2, 'c': 3}
myDict.setdefault('d',5)
print(myDict) # prints {'a': 12, 'b': 2, 'c': 3, 'd': 5}

If the setdefault() method is called with only one argument (the key), and the key does not exist in the dictionary, it will add the key and set the value of the key to None.

myDict = {'a': 12, 'b': 2}
myDict.setdefault('c')
print(myDict) # prints {'a': 12, 'b': 2, 'c': None}

ACCESS METHODS

get(): returns the value for the specified key, or a default value if the key is not found. If the key does not exist in the dictionary, the get() method will return a default value specified as an argument to the method. If no default value is specified, the get() method will return None.

flower_colors = {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}
print(flower_colors.get('rose')) # prints 'red'
print(flower_colors.get('lily')) # prints 'white'

here are two examples where the key 'orchid' is not found in the dictionary. In the first example, since no default value is specified, the get() method returns the default value None. In the second example, the default value is set to 'not found'

flower_colors = {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}
print(flower_colors.get('orchid')) # prints None
print(flower_colors.get('orchid','not found')) # prints not found

items(): returns a view object that displays a list of the dictionary's key-value pairs.

flower_colors = {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}
print(flower_colors.items()) # returns dict_items([('rose', 'red'), ('lily', 'white'), ('tulip', 'pink')])

keys(): returns a view object that displays a list of the dictionary's keys

flower_colors = {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}
print(flower_colors.keys()) # returns dict_keys(['rose', 'lily', 'tulip'])

values(): returns a view object that displays a list of the dictionary's values

flower_colors = {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}
print(flower_colors.values()) # returns dict_values(['red', 'white', 'pink'])

COPY METHODS

copy(): returns a copy of the dictionary

flower_colors = {'rose':'red','lily':'white','tulip':'pink'}
print(flower_colors.copy()) # prints {'rose': 'red', 'lily': 'white', 'tulip': 'pink'}

OTHER METHODS

fromkeys(): returns a new dictionary with keys from the given sequence and the specified value. It takes two arguments:

flowers = ('rose', 'tulips')
color = 'red'
print(dict.fromkeys(flowers,color)) # prints {'rose': 'red', 'tulips': 'red'}

len(): returns the length of an object. It is not a method of the dictionary data type specifically, but it can be used to find the number of key-value pairs in a dictionary.

myDict = {'a': 12, 'b': 2, 'c': 1}
len(myDict) # returns 3

4. DICTIONNARY COMPREHENSION

my_dict={str(i) + ' squared ': i**2 for i in range(4)}
print(my_dict)
# prints :
# {'0 squared ': 0, '1 squared ': 1, '2 squared ': 4, '3 squared ': 9}

my_dict = {'file1' : 1.1, 'file2' : 2, 'file3' : 0.5}
new_dict = {key : value for key, value in my_dict.items() if value < 1}
print(new_dict)
# prints : {'file3': 0.5}

5. MORE EXAMPLES

# sorting the keys based on values and storing the sorted keys in a list
my_dict = {'file1' : 1.1, 'file2' : 2, 'file3' :0.5}
sorted_list = sorted(my_dict, key=my_dict.get, reverse=True)
print(sorted_list) # prints ['file2', 'file1', 'file3']
# looping over a dictionnary
my_dict = {'file1' : 2022, 'file2' : 2023, 'file3' :2024}
for key, value in my_dict.items():
    print(f'{key}-{value}')
# prints :
# file1-2022
# file2-2023
# file3-2024
# filter font keys of Matplotlib's rcParams dictionnary :
font_keys = [key for key in plt.rcParams if key.startswith('font.')]
# prints :
# ['font.cursive', 'font.family', 'font.fantasy', 'font.monospace', 'font.sans-serif',
# 'font.serif', 'font.size', 'font.stretch', 'font.style', 'font.variant', 'font.weight']
# merging two dictionnaries :
dict1 = {'file1' : 1.1, 'file2' : 2, 'file3' :0.5}
dict2 = {'file4' : 1.1, 'file5' :2.2, 'file6' :1}
print(dict1 | dict2)
# prints {'file1': 1.1, 'file2': 2, 'file3': 0.5, 'file4': 1.1, 'file5': 2.2, 'file6': 1}

# merging two dictionnaries with a shared key !
dict1 = {'file1' : 1.1, 'file2' : 2, 'file3' :0.5}
dict2 = {'file3' : 1.1, 'file4' :2.2, 'file5' :1}
print(dict1 | dict2)
# prints {'file1': 1.1, 'file2': 2, 'file3': 1.1, 'file4': 2.2, 'file5': 1}

# this works too : 
print({**dict1,** dict2})
code snippet for merging dictionnaries