In this section, we will learn what dictionaries are and how to use them in Python.
What is Dictionary in Python? (Python Dict)
The Python Dictionary is a container object that can take values as part of its elements.
To some extents a dictionary object is like a Python List but with one exception! While we can access the elements of a list using the index number (by default elements have a number attached to them which is known as the index number), in python dictionary, we use something called `key` as the way to access the elements of a dictionary and the type of that key is not necessarily integer.
Create a Dictionary in Python: Dictionary Syntax
dictionaryVariable = { key1:value1, key2:value2, key3:value3, keyN:valueN }
`{}`: In order to create a dictionary in Python, we first start with a pair of braces `{}` and within that brace we put the entries of the dictionary. (Each pair of key-value in a dictionary is known as an entry or item).
`:`: We use colon to separate each `key` from its `value`.
`,`: Each key-value pair is separated using a comma `,`.
Python Dictionary Key
Keys in a dictionary are the way of accessing values! Each key can be any type of values like a simple string value, an integer number, a float number, a boolean value, or even the value that was assigned to a variable (meaning we can use an external variable as the key in a dictionary).
Note: be aware that in a dictionary, we can’t have duplicate keys. Basically, keys must be unique!
If we add a duplicate key to a dictionary, the value of the second key will replace the value of the first key! Essentially, applying a duplicate key on a dictionary will act as an update on the value of the old key.
Example: duplicate key in Python dictionary
dictionary = { "name":"John", "name":"Jack" } print(dictionary)
Output:
{'name': 'Jack'}
Note that we used two keys with the same name, but in the output we can see that the value of the second key replaced the value of the first key (update it) and we have only one key!
Python Dictionary Value
Values are the ones that we assign to keys in a dictionary. They are paired with keys.
Basically, you can’t have a value in a dictionary without a key!
The elements we set as the values in a dictionary could be of any type including string, integer, float, another dictionary, a list, a tuple, a set object etc. Basically, there’s no limit on what we can use as the value of a key in a dictionary.
Note that values can be duplicated as well! This is because values are not the method of accessing the elements of a dictionary! We use keys, for that matter.
Example: creating a dictionary in python
var = "lastName" dictionary = { 1: 10, "name":"John", "name":"Jack", True: False, False: True, 2.3:40, var:"John Doe" } print(dictionary) print(dictionary[var]) print(dictionary[2.3])
Output:
{1: False, 'name': 'Jack', False: True, 2.3: 40, 'lastName': 'John Doe'} John Doe 40
Note that the value of the `var` variable is replaced with its value when we printed the dictionary to the output stream. This means even though we can use an external variable as a key in a dictionary, in reality, it’s the value of that variable that will be used as the key!
Python get Value from Dictionary: How to access values in Python dictionary?
In order to access the values of a dictionary in python, we use a pair of brackets `[]` as the syntax below shows:
dictionaryName[key]
Within the body of this bracket, we put the name of the key that we want to get its value in a dictionary.
Example: accessing dictionary in python
var = "lastName" dictionary = { 1: 10, "name":"John", True: False, False: True, 2.3:40, var:"John Doe" } print(dictionary[True]) print(dictionary[False]) print(dictionary[1]) print(dictionary[var]) print(dictionary["lastName"]) print(dictionary[2.3])
Output:
False True False John Doe John Doe 40
Python Add to Dictionary (Append Dictionary Python)
In Python dictionary, there’s no method like `add()` or `append()` etc. that you saw for a list object! Instead, if we want to add a new key-value pair to a dictionary, all we need to do is to call the target dictionary with the key that we want to add to it on the left side of the assignment operator `=` and then on the right side of this operator put the value. That way, if the key did not exist in the dictionary, it will be added to it. But if the dictionary has already the key, then the value will be used to update (replace) the old value of the target key.
Example: Python adding to Dictionary (append dict python)
employee = { "name":"John", "lastName":"Doe" } employee["age"] = 20 employee["email"] = "[email protected]" print(employee)
Output:
{'name': 'John', 'lastName': 'Doe', 'age': 20, 'email': '[email protected]'}
In this example, the `employee` dictionary has initially two keys in it with the named `name` and `lastName`.
But then we called the `employee` on the left side of the assignment operator with two keys that were not in that dictionary. So what happened is that the execution engine added these two keys as the new keys in the `employee` dictionary.
That’s how we got the output of the example.
Print Dictionary in Python
The simplest method of printing the elements of a dictionary is to directly pass the dictionary object as the argument of the `print()` function and then its keys and values will be printed to the output stream.
But if the purpose is to print just the values of a dictionary to the output stream, then we can use the `for in` loop. Basically, if we pass the dictionary as the iterable object in a for loop, the values of that dictionary will return and we can print them within the body of the for loop.
Also, if the purpose is to just print the keys of a dictionary, then there’s a method named `keys()` that can be called which returns a list of keys of the target dictionary object. That means we can use this method in a `for in` loop and then print the keys within the body of that loop as well.
Example: printing a dictionary in Python
employee = { "name":"John", "lastName":"Doe" } employee["age"] = 20 employee["email"] = "[email protected]" print(employee) print("***value***") for value in employee: print(value) print("***keys***") for key in employee.keys(): print(key)
Output:
{'name': 'John', 'lastName': 'Doe', 'age': 20, 'email': '[email protected]'} ***value*** name lastName age email ***keys*** name lastName age email
Python Dictionary for Loop
Using the `for` loop, we can iterate through either keys, values or keys and values together of a dictionary object.
Now, if the purpose is to iterate through the values of a dictionary, then all we need to do is to use that dictionary as the iterable object of the for loop. (Note that there’s a method called `values()` which can be called using the target dictionary and that will also return the values of the dictionary and it could be used as the iterable object of the for loop)
If the purpose is to iterate through the keys of a dictionary, then we can call the `keys()` method of the target dictionary and that will return a sequence of keys of the dictionary which could be used as the iterable object of the for loop.
And finally, if the purpose is to loop through the `keys` and `values` of a dictionary at the same time, then there’s a method called `items()` that if called upon a dictionary, the return value will be a sequence with each element is a pair of key and value of that dictionary which then could be used as the iterable object of a for loop.
Example: python for loop and dictionary
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]" } print("Using the dictionary itself as the iterable object of the for loop:") for value in employee: print(value) print("Using the result of calling the values() method of the dictionary as the iterab object of the for loop:") for value1 in employee: print(value1) print("Using the result of calling the keys() method of the dictionary as the iterable object of the for loop:") for key in employee: print(key) print("using the result of calling the items() method of the dictionary as the iterable object of the for loop:") for key,value in employee.items(): print(f"The key is: {key} and the value is: {value}")
Output:
Using the dictionary itself as the iterable object of the for loop: name lastName age email Using the result of calling the values() method of the dictionary as the iterab object of the for loop: name lastName age email Using the result of calling the keys() method of the dictionary as the iterable object of the for loop: name lastName age email using the result of calling the items() method of the dictionary as the iterable object of the for loop: The key is: name and the value is: John The key is: lastName and the value is: Doe The key is: age and the value is: 20 The key is: email and the value is: [email protected]
Python List of Dictionaries
Python dictionaries can be used as the elements of other container objects like List as well.
Example: creating a list of dictionary in python
list1 = [ {"name":"John", "age":20}, {"name":"Jack","age":10}, {"name":"Omid","age":4} ] print(list1[0]["name"]) print(list1[1]["name"]) print(list1[2]["name"])
Output:
John Jack Omid
Python Dictionary of Lists
List object could be used as part of a dictionary as well. But be aware that we can use lists only as the values of a dictionary and not its keys!
Example: creating a dictionary of lists
li1 = [1,2,3] li2 = [4,5,6] li3 = [7,8,9] dictionary = { "list1":li1, "list2":li2, "list3":li3 } print(dictionary)
Output:
{'list1': [1, 2, 3], 'list2': [4, 5, 6], 'list3': [7, 8, 9]}
Python Dictionary of Dictionaries (Python Nested Dictionary)
A dictionary object can become the value for a key in another dictionary object! In that case, the inner dictionary is called a nested dictionary.
Example: creating dictionary of dictionaries
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]", "address":{ "state":"California", "city":"Los Angeles" } } print(employee["address"]["state"])
Output:
California
Python Merge Dictionaries
The simplest method of merging one dictionary to another one is by using the `update()` method.
This method can be invoked by a dictionary object and it takes another dictionary as its argument.
It then checks every key of the argument dictionary and either add each key to the source dictionary (if the key is not already defined in the source dictionary) or update the value of the target key with the new value in the argument dictionary (if the source already has the key within its body).
Example: merging dictionaries in Python
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]", } address={ "state":"California", "city":"Los Angeles" } employee.update(address) print(employee)
Output:
{'name': 'John', 'lastName': 'Doe', 'age': 20, 'email': '[email protected]', 'state': 'California', 'city': 'Los Angeles'}
Length of Dictionary in Python
Using the `len()` function, we can get the length (the number of key-value pairs) of a dictionary.
To do this, all we need to do is to pass the target dictionary as the argument of the `len()` function.
Example: getting the length of dictionary in python
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]" } print(f"The length of the employee dictionary is: {len(employee)}")
Output:
The length of the employee dictionary is: 4
Remove Key from Dictionary Python
There are two methods by which we can remove a pair of key-value from a dictionary.
The first method is to use the `pop()` method. This method is part of the methods supported by dictionary objects.
Using the `pop()` method, all we need to do is to pass the target key we want to remove from the dictionary as the argument of the method and it will then remove the key (as well as its value) from the dictionary.
The other method of removing a key from a dictionary is by using the `del` operator. The `del` operator is explained in the Python del section.
Example: removing key from dictionary in python
employee = { "name":"John", "lastName":"Doe", "age":20, "email":"[email protected]", "address":{ "state":"California", "city":"Los Angeles" } } res = employee.pop("name") print(res) print(employee)
Output:
John {'lastName': 'Doe', 'age': 20, 'email': '[email protected]', 'address': {'state': 'California', 'city': 'Los Angeles'}}
How are Python Dictionaries Different from Python Lists? (Python List vs Dictionary)
The main difference between a dictionary and a list object is that in case of a dictionary object we explicitly set the key for each value. This key could be of any type, including integer!
But for the list objects, the keys are implicitly set and they are only of type integer!