0% found this document useful (0 votes)
2 views

Dictionary

The document provides an overview of Python dictionaries, explaining their structure as key:value pairs, their properties such as being ordered and changeable, and methods for accessing, modifying, and removing items. It also covers how to create dictionaries using both curly brackets and the dict() constructor, as well as how to loop through them and copy them. Additionally, it discusses nested dictionaries and the importance of ensuring keys are unique within a dictionary.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Dictionary

The document provides an overview of Python dictionaries, explaining their structure as key:value pairs, their properties such as being ordered and changeable, and methods for accessing, modifying, and removing items. It also covers how to create dictionaries using both curly brackets and the dict() constructor, as well as how to loop through them and copy them. Additionally, it discusses nested dictionaries and the importance of ensuring keys are unique within a dictionary.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Dictionaries

In [1]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6
and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Example Create and print a dictionary

In [2]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items Dictionary items are ordered, changeable, and do not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example Print the "brand" value of the dictionary:

In [3]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ford

Ordered or Unordered?

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Unordered means that the items do not have a defined order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example Duplicate values will overwrite existing values:

In [4]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example Print the number of items in the dictionary:

In [6]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))

Dictionary Items - Data Types The values in dictionary items can be of any data type:

Example String, int, boolean, and list data types:

In [13]:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type("thisdict"))
print(type("ford"))
print(type(False))
print(type(1964))
print(type(["red", "white", "blue"]))

<class 'str'>
<class 'str'>
<class 'bool'>
<class 'int'>
<class 'list'>

The dict() Constructor It is also possible to use the dict() constructor to make a dictionary.

Example Using the dict() method to make a dictionary:

In [14]:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

{'name': 'John', 'age': 36, 'country': 'Norway'}

Accessing Items You can access the items of a dictionary by referring to its key name, inside square brackets:

Example Get the value of the "model" key:

In [16]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)

Mustang

There is also a method called get() that will give you the same result:

Example Get the value of the "model" key:

In [17]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)

Mustang

Get Keys The keys() method will return a list of all the keys in the dictionary.

Example Get a list of the keys:

In [18]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)

dict_keys(['brand', 'model', 'year'])

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
Example Add a new item to the original dictionary, and see that the keys list gets updated as well:

In [19]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

dict_keys(['brand', 'model', 'year'])


dict_keys(['brand', 'model', 'year', 'color'])

Get Values The values() method will return a list of all the values in the dictionary.

Example Get a list of the values:

In [20]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)

dict_values(['Ford', 'Mustang', 1964])

The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.

Example Make a change in the original dictionary, and see that the values list gets updated as well:

In [21]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

dict_values(['Ford', 'Mustang', 1964])


dict_values(['Ford', 'Mustang', 2020])

Example Add a new item to the original dictionary, and see that the values list gets updated as well:

In [22]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

dict_values(['Ford', 'Mustang', 1964])


dict_values(['Ford', 'Mustang', 1964, 'red'])

Get Items The items() method will return each item in a dictionary, as tuples in a list.

Example Get a list of the key:value pairs

In [23]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x)

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

Example Make a change in the original dictionary, and see that the items list gets updated as well:

In [24]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])


dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])

Example Add a new item to the original dictionary, and see that the items list gets updated as well:

In [25]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])


dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])

Check if Key Exists To determine if a specified key is present in a dictionary use the in keyword:

Example Check if "model" is present in the dictionary:

In [26]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Yes, 'model' is one of the keys in the thisdict dictionary

Change Values You can change the value of a specific item by referring to its key name:

Example Change the "year" to 2018:

In [29]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Update Dictionary The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.


Example Update the "year" of the car by using the update() method:

In [30]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Adding Items Adding an item to the dictionary is done by using a new index key and assigning a value to it:

In [31]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Update Dictionary The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be
added.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example Add a color item to the dictionary by using the update() method:

In [32]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items There are several methods to remove items from a dictionary:

Example The pop() method removes the item with the specified key name:

In [33]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

{'brand': 'Ford', 'year': 1964}

Example The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

In [34]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang'}

Example The del keyword removes the item with the specified key name:

In [35]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

{'brand': 'Ford', 'year': 1964}


Example The del keyword can also delete the dictionary completely:

In [36]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

---------------------------------------------------------------------------NameError Traceback (most recent call las


1 thisdict = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6 del thisdict
----> 7 print(thisdict) #this will cause an error because "thisdict" no longer exists.
NameError: name 'thisdict' is not defined

Example The clear() method empties the dictionary:

In [37]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

{}

Loop Through a Dictionary You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example Print all key names in the dictionary, one by one:

In [43]:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)

brand
model
year

Example You can use the keys() method to return the keys of a dictionary:

In [44]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)

brand
model
year

Example Print all values in the dictionary, one by one:

In [39]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])

Ford
Mustang
1964

Example You can also use the values() method to return values of a dictionary:
In [42]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)

Ford
Mustang
1964

Example Loop through both keys and values, by using the items() method:

In [ ]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)

Copy a Dictionary You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in
dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

In [ ]: Example
Make a copy of a dictionary with the copy() method:

In [45]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Another way to make a copy is to use the built-in function dict().

Example Make a copy of a dictionary with the dict() function:

In [46]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Nested Dictionaries A dictionary can contain dictionaries, this is called nested dictionaries.

Example Create a dictionary that contain three dictionaries:

In [47]:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)

{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Or, if you want to add three dictionaries into a new dictionary:

Example Create three dictionaries, then create one dictionary that will contain the other three dictionaries:

In [48]:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

print(myfamily)

{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}

Access Items in Nested Dictionaries To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary:

Example Print the name of child 2:

In [49]:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily["child2"]["name"])

Tobias

Loop Through Nested Dictionaries You can loop through a dictionary by using the items() method like this:

Example Loop through the keys and values of all nested dictionaries:

In [1]: myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}

# Iterate through the dictionary


for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])

child1
name: Emil
year: 2004
child2
name: Tobias
year: 2007
child3
name: Linus
year: 2011

Dictionary Methods Python has a set of built-in methods that you can use on dictionaries.

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

You might also like