Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value
pair. Key value is provided in the dictionary to make it more optimized.
Note – Keys in a dictionary doesn’t allows Polymorphism.
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value
. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: 'Geeks', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update()
method. Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}, 'Value_set': (2, 3, 4)}
In order to access the items of a dictionary refer to its key name.Key can be used inside square brackets.
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in acessing the element from a dictionary.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
In order to access the value of any key in nested dictionary, use indexing [] syntax.
# Creating a Dictionary
Dict = {'Dict1': {1: 'Geeks'},
'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
del
keywordIn Python Dictionary, deletion of keys can be done by using the del
keyword. Using del keyword, specific values from a dictionary as well as whole dictionary can be deleted. Items in a Nested dictionary can also be deleted by using del keyword and providing specific nested key and particular key to be deleted from that nested Dictionary.
Note- del Dict
will delete the entire dictionary and hence printing it after deletion will raise an Error.
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
'B' : {1 : 'Geeks', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
Output:
Initial Dictionary:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}
Deleting a specific key:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}
Deleting a key from Nested Dictionary:
{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}
pop()
methodPop()
method is used to return and delete the value of the key specified.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(1)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))
Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks
popitem()
methodThe popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.
# Creating Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))
Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')
clear()
methodAll the items from a dictionary can be deleted at once by using clear()
method.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)
Output:
Deleting Entire Dictionary:
{}
In this article, you will learn how to work with Python Dictionaries, an incredibly helpful built-in data type that you will definitely use during your projects.
In particular, you will learn:
At the end of this article, we will dive into a simple project to apply your knowledge: we will write a function that creates and returns a dictionary with a particular purpose.
Let’s begin! 🔅
Let’s start by discussing the importance of dictionaries. To illustrate this, let me do a quick comparison with another data type that you are probably familiar with: lists.
When you work with lists in Python, you can access an element using a index, an integer that describes the position of the element in the list. Indices start from zero for the first element and increase by one for every subsequent element in the list. You can see an example right here:
But what if we need to store two related values and keep this “connection” in our code? Right now, we only have single, independent values stored in a list.
Let’s say that we want to store names of students and “connect” each name with the grades of each particular student. We want to keep the “connection” between them. How would you do that in Python?
If you use nested lists, things would get very complex and inefficient after adding only a few items because you would need to use two or more indices two access each value, depending on the final list. This is where Python Dictionaries come to the rescue.
A Python dictionary looks like this (see below). With a dictionary, you can “connect” a value to another value to represent the relationship between them in your code. In this example,“Gino” is “connected” to the integer 15 and the string “Nora” is “connected” to the integer 30.
Let’s see the different elements that make a dictionary.
Since a dictionary “connects” two values, it has two types of elements:
These two elements form what is called a key-value pair (a key with its corresponding value).
This is an example of a Python Dictionary mapping the string “Gino” to the number 15 and the string “Nora” to the number 30:
>>> {"Gino": 15, "Nora": 30}
{ }
.💡 Tips:
{}
.Not every value can be a key in a Python dictionary. Keys have to follow a set of rules:
According to the Python Documentation:
It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.
You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like
append()
andextend()
.
💡 Note: Values have no specific rules, they can be either mutable or immutable values.
Now let’s see how we can work with dictionaries in Python. We are going to access, add, modify, and delete key-value pairs.
We will start working with this dictionary, assigned to the ages
variable:
>>> ages = {"Gino": 15, "Nora": 30}
If we need to access the value associated with a specific key, we write the name of the variable that references the dictionary followed by square brackets []
and, within square brackets, the key that corresponds to the value:
<variable>[<key>]
This is an example of how we can access the value that corresponds to the string "Gino"
:
>>> ages = {"Gino": 15, "Nora": 30}
>>> ages["Gino"]
15
Notice that the syntax is very similar to indexing a string, tuple, or list, but now we are using the key as the index instead of an integer.
If we want to access the value that corresponds to “Nora”, we would do this:
>>> ages = {"Gino": 15, "Nora": 30}
>>> ages["Nora"]
30
💡 Tip: If you try to access a key that does not exist in the dictionary, you will get a KeyError
:
>>> ages = {"Gino": 15, "Nora": 30}
>>> ages["Talina"]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
ages["Talina"]
KeyError: 'Talina'
If a key-value pair doesn’t exist in the dictionary, we can add it. To do this, we write the variable that references the dictionary followed by the key within square brackets, an equal sign, and the new value:
This is an example in IDLE:
>>> ages = {"Gino": 15, "Nora": 30}
# Add the key-value pair "Talina": 24
>>> ages["Talina"] = 24
# The dictionary now has this key-value pair
>>> ages
{'Gino': 15, 'Nora': 30, 'Talina': 24}
To modify the value associated to a specific key, we use the same syntax that we use to add a new key-value pair, but now we will be assigning the new value to an existing key:
>>> ages = {"Gino": 15, "Nora": 30}
# The key "Gino" already exists in the dictionary, so its associated value
# will be updated to 45.
>>> ages["Gino"] = 45
# The value was updated to 45.
>>> ages
{'Gino': 45, 'Nora': 30}
To delete a key-value pair, you would use the del
keyword followed by the name of the variable that references the dictionary and, within square brackets []
, the key of the key-value pair:
This is an example in IDLE:
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
# Delete the key-value pair "Gino": 15.
>>> del ages["Gino"]
# The key-value pair was deleted.
>>> ages
{'Nora': 30, 'Talina': 45}
Sometimes, it can be very helpful to check if a key already exists in a dictionary (remember that keys have to be unique).
According to the Python Documentation:
To check whether a single key is in the dictionary, use the
in
keyword.
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> "Talina" in ages
True
>>> "Gino" in ages
True
>>> "Lulu" in ages
False
The in
operator checks the keys, not the values. If we write this:
>>> 15 in ages
False
We are checking if the key 15 is in the dictionary, not the value. This is why the expression evaluates to False
.
💡 Tip: You can use the in
operator to check if a value is in a dictionary with .values().
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> 30 in ages.values()
True
>>> 10 in ages.values()
False
The length of a dictionary is the number of key-value pairs it contains. You can check the length of a dictionary with the len() function that we commonly use, just like we check the length of lists, tuples, and strings:
# Two key-value pairs. Length 2.
>>> ages = {"Gino": 15, "Nora": 30}
>>> len(ages)
2
# Three key-value pairs. Length 3.
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> len(ages)
3
You can iterate over dictionaries using a for loop. There are various approaches to do this and they are all equally relevant. You should choose the approach that works best for you, depending on what you are trying to accomplish.
We can iterate over the keys of a dictionary like this:
for <key> in <dictionary>:
# Do this
For example:
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> for student in ages:
print(student)
Gino
Nora
Talina
To do this, we need to use the built-in method .items(), which allows us to iterate over the key-value pairs as tuples of this format (key, value)
.
for <key-value-pair-as-tuple> in <dictionary>.items():
# Do this
For example:
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> for pair in ages.items():
print(pair)
('Gino', 15)
('Nora', 30)
('Talina', 45)
With .items() and for loops, you can use the power of a tuple assignment to directly assign the keys and values to individual variables that you can use within the loop:
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
# Tuple assignment to assign the key to the variable key
# and the value to the variable value.
>>> for key, value in ages.items():
print("Key:", key, "; Value:", value)
Key: Gino ; Value: 15
Key: Nora ; Value: 30
Key: Talina ; Value: 45
You can iterate over the values of a dictionary using the .values() method.
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> for age in ages.values():
print(age)
15
30
45
Dictionaries include very helpful built-in methods that can save you time and work to perform common functionality:
This method removes all the key-value pairs from the dictionary.
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> ages.clear()
>>> ages
{}
This method returns the value associated with the key. Otherwise, it returns the default value that was provided as the second argument (this second argument is optional).
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> ages.get("Nora")
30
>>> ages.get("Nor", "Not Found")
'Not Found'
If you don’t add a second argument, this is equivalent to the previous syntax with square brackets []
that you learned:
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> ages["Nora"]
30
>>> ages.get("Nora")
30
This method removes the key-value pair from the dictionary and returns the value.
>>> ages = {"Gino": 15, "Nora": 30, "Talina": 45}
>>> ages.pop("Talina")
45
>>> ages
{'Gino': 15, 'Nora': 30}
This method replaces the values of a dictionary with the values of another dictionary only for those keys that exist in both dictionaries.
An example of this would be a dictionary with the original grades of three students (see code below). We only want to replace the grades of the students who took the make-up exam (in this case, only one student took the make-up exam, so the other grades should remain unchanged).
>>> grades = {"Gino": 0, "Nora": 98, "Talina": 99}
>>> new_grades = {"Gino": 67}
>>> grades.update(new_grades)
>>> grades
{'Gino': 67, 'Nora': 98, 'Talina': 99}
By using the .update() method, we could update the value associated with the string “Gino” in the original dictionary since this is the only common key in both dictionaries.
The original value would be replaced by the value associated with this key in the dictionary that was passed as argument to .update().
💡 Tips: To learn more about dictionary methods, I recommend reading this article in the Python Documentation.
Now you will apply your knowledge by writing a function freq_dict
that creates and returns a dictionary with the frequency of each element of a list, string, or tuple (the number of times the element appears). The elements will be the keys and the frequencies will be the values.
We will be writing the function step-by-step to see the logic behind each line of code.
data
.def freq_dict(data):
def freq_dict(data):
freq = {}
def freq_dict(data):
freq = {}
for elem in data:
def freq_dict(data):
freq = {}
for elem in data:
if elem in freq:
freq[elem] += 1
else:
freq[elem] = 1
def freq_dict(data):
freq = {}
for elem in data:
if elem in freq:
freq[elem] += 1
else:
freq[elem] = 1
return freq
🔔 Important: Since we are assigning the elements as the keys of the dictionary, they have to be of an immutable data type.
Here we have an example of the use of this function. Notice how the dictionary maps each character of the string to how many times it occurs.
>>> def freq_dict(data):
freq = {}
for elem in data:
if elem in freq:
freq[elem] += 1
else:
freq[elem] = 1
return freq
>>> freq_dict("Hello, how are you?")
{'H': 1, 'e': 2, 'l': 2, 'o': 3, ',': 1, ' ': 3, 'h': 1, 'w': 1, 'a': 1, 'r': 1, 'y': 1, 'u': 1, '?': 1}
This is another example applied to a list of integers:
>>> def freq_dict(data):
freq = {}
for elem in data:
if elem in freq:
freq[elem] += 1
else:
freq[elem] = 1
return freq
>>> freq_dict([5, 2, 6, 2, 6, 5, 2, 2, 2])
{5: 2, 2: 5, 6: 2}
Great Work! Now we have the final function.
Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects.
Here’s what you’ll learn in this tutorial: You’ll cover the basic characteristics of Python dictionaries and learn how to access and manage dictionary data. Once you have finished this tutorial, you should have a good sense of when a dictionary is the appropriate data type to use, and how to do so.
Dictionaries and lists share the following characteristics:
Dictionaries differ from lists primarily in how elements are accessed:
Table of Contents
Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}
). A colon (:
) separates each key from its associated value:
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
The following defines a dictionary that maps a location to the name of its corresponding Major League Baseball team:
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
You can also construct a dictionary with the built-in dict()
function. The argument to dict()
should be a sequence of key-value pairs. A list of tuples works well for this:
d = dict([
(<key>, <value>),
(<key>, <value),
.
.
.
(<key>, <value>)
])
MLB_team
can then also be defined this way:
>>> MLB_team = dict([
... ('Colorado', 'Rockies'),
... ('Boston', 'Red Sox'),
... ('Minnesota', 'Twins'),
... ('Milwaukee', 'Brewers'),
... ('Seattle', 'Mariners')
... ])
If the key values are simple strings, they can be specified as keyword arguments. So here is yet another way to define MLB_team
:
>>> MLB_team = dict(
... Colorado='Rockies',
... Boston='Red Sox',
... Minnesota='Twins',
... Milwaukee='Brewers',
... Seattle='Mariners'
... )
Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list. All three of the definitions shown above appear as follows when displayed:
>>> type(MLB_team)
<class 'dict'>
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
The entries in the dictionary display in the order they were defined. But that is irrelevant when it comes to retrieving them. Dictionary elements are not accessed by numerical index:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
MLB_team[1]
KeyError: 1
Of course, dictionary elements must be accessible somehow. If you don’t get them by index, then how do you get them?
A value is retrieved from a dictionary by specifying its corresponding key in square brackets ([]
):
>>> MLB_team['Minnesota']
'Twins'
>>> MLB_team['Colorado']
'Rockies'
If you refer to a key that is not in the dictionary, Python raises an exception:
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
Adding an entry to an existing dictionary is simply a matter of assigning a new key and value:
>>> MLB_team['Kansas City'] = 'Royals'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}
If you want to update an entry, you can just assign a new value to an existing key:
>>> MLB_team['Seattle'] = 'Seahawks'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}
To delete an entry, use the del
statement, specifying the key to delete:
>>> del MLB_team['Seattle']
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}
Begone, Seahawks! Thou art an NFL team.
You may have noticed that the interpreter raises the same exception, KeyError
, when a dictionary is accessed with either an undefined key or by a numeric index:
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
>>> MLB_team[1]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
MLB_team[1]
KeyError: 1
In fact, it’s the same error. In the latter case, [1]
looks like a numerical index, but it isn’t.
You will see later in this tutorial that an object of any immutable type can be used as a dictionary key. Accordingly, there is no reason you can’t use integers:
>>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d[0]
'a'
>>> d[2]
'c'
In the expressions MLB_team[1]
, d[0]
, and d[2]
, the numbers in square brackets appear as though they might be indices. But they have nothing to do with the order of the items in the dictionary. Python is interpreting them as dictionary keys. If you define this same dictionary in reverse order, you still get the same values using the same keys:
>>> d = {3: 'd', 2: 'c', 1: 'b', 0: 'a'}
>>> d
{3: 'd', 2: 'c', 1: 'b', 0: 'a'}
>>> d[0]
'a'
>>> d[2]
'c'
The syntax may look similar, but you can’t treat a dictionary like a list:
>>> type(d)
<class 'dict'>
>>> d[-1]
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
d[-1]
KeyError: -1
>>> d[0:2]
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
d[0:2]
TypeError: unhashable type: 'slice'
>>> d.append('e')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
d.append('e')
AttributeError: 'dict' object has no attribute 'append'
Note: Although access to items in a dictionary does not depend on order, Python does guarantee that the order of items in a dictionary is preserved. When displayed, items will appear in the order they were defined, and iteration through the keys will occur in that order as well. Items added to a dictionary are added at the end. If items are deleted, the order of the remaining items is retained.
Defining a dictionary using curly braces and a list of key-value pairs, as shown above, is fine if you know all the keys and values in advance. But what if you want to build a dictionary on the fly?
You can start by creating an empty dictionary, which is specified by empty curly braces. Then you can add new keys and values one at a time:
>>> person = {}
>>> type(person)
<class 'dict'>
>>> person['fname'] = 'Joe'
>>> person['lname'] = 'Fonebone'
>>> person['age'] = 51
>>> person['spouse'] = 'Edna'
>>> person['children'] = ['Ralph', 'Betty', 'Joey']
>>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}
Once the dictionary is created in this way, its values are accessed the same way as any other dictionary:
>>> person
{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna',
'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}
>>> person['fname']
'Joe'
>>> person['age']
51
>>> person['children']
['Ralph', 'Betty', 'Joey']
Retrieving the values in the sublist or subdictionary requires an additional index or key:
>>> person['children'][-1]
'Joey'
>>> person['pets']['cat']
'Sox'
This example exhibits another feature of dictionaries: the values contained in the dictionary don’t need to be the same type. In person
, some of the values are strings, one is an integer, one is a list, and one is another dictionary.
Just as the values in a dictionary don’t need to be of the same type, the keys don’t either:
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo[42]
'aaa'
>>> foo[2.78]
'bbb'
>>> foo[True]
'ccc'
Here, one of the keys is an integer, one is a float, and one is a Boolean. It’s not obvious how this would be useful, but you never know.
Notice how versatile Python dictionaries are. In MLB_team
, the same piece of information (the baseball team name) is kept for each of several different geographical locations. person
, on the other hand, stores varying types of data for a single person.
You can use dictionaries for a wide range of purposes because there are so few limitations on the keys and values that are allowed. But there are some. Read on!
Almost any type of value can be used as a dictionary key in Python. You just saw this example, where integer, float, and Boolean objects are used as keys:
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
You can even use built-in objects like types and functions:
>>> d = {int: 1, float: 2, bool: 3}
>>> d
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}
>>> d[float]
2
>>> d = {bin: 1, hex: 2, oct: 3}
>>> d[oct]
3
However, there are a couple restrictions that dictionary keys must abide by.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once.
You saw above that when you assign a value to an already existing dictionary key, it does not add the key a second time, but replaces the existing value:
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
>>> MLB_team['Minnesota'] = 'Timberwolves'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Timberwolves',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
Similarly, if you specify a key a second time during the initial creation of a dictionary, the second occurrence will override the first:
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Timberwolves',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners',
... 'Minnesota': 'Twins'
... }
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
Begone, Timberwolves! Thou art an NBA team. Sort of.
Secondly, a dictionary key must be of a type that is immutable. You have already seen examples where several of the immutable types you are familiar with—integer, float, string, and Boolean—have served as dictionary keys.
A tuple can also be a dictionary key, because tuples are immutable:
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
>>> d[(1,1)]
'a'
>>> d[(2,1)]
'c'
However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable:
>>> d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
TypeError: unhashable type: 'list'
Technical Note: Why does the error message say “unhashable”?
Technically, it is not quite correct to say an object must be immutable to be used as a dictionary key. More precisely, an object must be hashable, which means it can be passed to a hash function. A hash function takes data of arbitrary size and maps it to a relatively simpler fixed-size value called a hash value (or simply hash), which is used for table lookup and comparison.
Python’s built-in hash()
function returns the hash value for an object which is hashable, and raises an exception for an object which isn’t:
>>> hash('foo')
11132615637596761
>>> hash([1, 2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
All of the built-in immutable types you have learned about so far are hashable, and the mutable container types (lists and dictionaries) are not. So for present purposes, you can think of hashable and immutable as more or less synonymous.
In future tutorials, you will encounter mutable objects which are also hashable.
By contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.
There is also no restriction against a particular value appearing in a dictionary multiple times:
>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
{0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d[0] == d[1] == d[2]
True
You have already become familiar with many of the operators and built-in functions that can be used with strings, lists, and tuples. Some of these work with dictionaries as well.
For example, the in
and not in
operators return True
or False
according to whether the specified operand occurs as a key in the dictionary:
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
>>> 'Milwaukee' in MLB_team
True
>>> 'Toronto' in MLB_team
False
>>> 'Toronto' not in MLB_team
True
You can use the in
operator together with short-circuit evaluation to avoid raising an error when trying to access a key that is not in the dictionary:
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
>>> 'Toronto' in MLB_team and MLB_team['Toronto']
False
In the second case, due to short-circuit evaluation, the expression MLB_team['Toronto']
is not evaluated, so the KeyError
exception does not occur.
The len()
function returns the number of key-value pairs in a dictionary:
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
>>> len(MLB_team)
5
As with strings and lists, there are several built-in methods that can be invoked on dictionaries. In fact, in some cases, the list and dictionary methods share the same name. (In the discussion on object-oriented programming, you will see that it is perfectly acceptable for different types to have methods with the same name.)
The following is an overview of methods that apply to dictionaries:
d.clear()
Clears a dictionary.
d.clear()
empties dictionary d
of all key-value pairs:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> d.clear()
>>> d
{}
d.get(<key>[, <default>])
Returns the value for a key if it exists in the dictionary.
The Python dictionary .get()
method provides a convenient way of getting the value of a key from a dictionary without checking ahead of time whether the key exists, and without raising an error.
d.get(<key>)
searches dictionary d
for <key>
and returns the associated value if it is found. If <key>
is not found, it returns None
:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> print(d.get('b'))
20
>>> print(d.get('z'))
None
If <key>
is not found and the optional <default>
argument is specified, that value is returned instead of None
:
>>> print(d.get('z', -1))
-1
d.items()
Returns a list of key-value pairs in a dictionary.
d.items()
returns a list of tuples containing the key-value pairs in d
. The first item in each tuple is the key, and the second item is the key’s value:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
>>> list(d.items())[1][0]
'b'
>>> list(d.items())[1][1]
20
d.keys()
Returns a list of keys in a dictionary.
d.keys()
returns a list of all keys in d
:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.keys())
['a', 'b', 'c']
d.values()
Returns a list of values in a dictionary.
d.values()
returns a list of all values in d
:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.values())
[10, 20, 30]
Any duplicate values in d
will be returned as many times as they occur:
>>> d = {'a': 10, 'b': 10, 'c': 10}
>>> d
{'a': 10, 'b': 10, 'c': 10}
>>> list(d.values())
[10, 10, 10]
Technical Note: The .items()
, .keys()
, and .values()
methods actually return something called a view object. A dictionary view object is more or less like a window on the keys and values. For practical purposes, you can think of these methods as returning lists of the dictionary’s keys and values.
d.pop(<key>[, <default>])
Removes a key from a dictionary, if it is present, and returns its value.
If <key>
is present in d
, d.pop(<key>)
removes <key>
and returns its associated value:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('b')
20
>>> d
{'a': 10, 'c': 30}
d.pop(<key>)
raises a KeyError
exception if <key>
is not in d
:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
d.pop('z')
KeyError: 'z'
If <key>
is not in d
, and the optional <default>
argument is specified, then that value is returned, and no exception is raised:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z', -1)
-1
>>> d
{'a': 10, 'b': 20, 'c': 30}
d.popitem()
Removes a key-value pair from a dictionary.
d.popitem()
removes a random, arbitrary key-value pair from d
and returns it as a tuple:
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.popitem()
('c', 30)
>>> d
{'a': 10, 'b': 20}
>>> d.popitem()
('b', 20)
>>> d
{'a': 10}
If d
is empty, d.popitem()
raises a KeyError
exception:
>>> d = {}
>>> d.popitem()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
d.popitem()
KeyError: 'popitem(): dictionary is empty'
d.update(<obj>)
Merges a dictionary with another dictionary or with an iterable of key-value pairs.
If <obj>
is a dictionary, d.update(<obj>)
merges the entries from <obj>
into d
. For each key in <obj>
:
d
, the key-value pair from <obj>
is added to d
.d
, the corresponding value in d
for that key is updated to the value from <obj>
.Here is an example showing two dictionaries merged together:
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d2 = {'b': 200, 'd': 400}
>>> d1.update(d2)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
In this example, key 'b'
already exists in d1
, so its value is updated to 200
, the value for that key from d2
. However, there is no key 'd'
in d1
, so that key-value pair is added from d2
.
<obj>
may also be a sequence of key-value pairs, similar to when the dict()
function is used to define a dictionary. For example, <obj>
can be specified as a list of tuples:
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update([('b', 200), ('d', 400)])
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
Or the values to merge can be specified as a list of keyword arguments:
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update(b=200, d=400)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
In this tutorial, you covered the basic properties of the Python dictionary and learned how to access and manipulate dictionary data.
Lists and dictionaries are two of the most frequently used Python types. As you have seen, they have several similarities, but differ in how their elements are accessed. Lists elements are accessed by numerical index based on order, and dictionary elements are accessed by key
Because of this difference, lists and dictionaries tend to be appropriate for different circumstances. You should now have a good feel for which, if either, would be best for a given situation.
Dictionary in Python
Python Tutorial for Beginners: Dictionaries - Working with Key-Value Pairs
Python Dictionaries || Python Tutorial || Learn Python Programming
How To Use Dictionaries In Python
Dictionary In Python | Python Dictionary Tutorial
Beginner’s Guide to Python - Dictionaries and For Loops
#python #web-development