0% found this document useful (0 votes)
3 views41 pages

Python Dictionaries Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views41 pages

Python Dictionaries Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Session 09

Dictionaries

Python @ Sinet
SINET EDUCATION

SINET EDUCATION [Link]


Python Collections (Arrays)

There are four collection data types in the Python programming


language:
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
Dictionary is a collection which is ordered** and changeable. No
duplicate members.

SINET EDUCATION [Link]


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:

SINET EDUCATION [Link]


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

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

SINET EDUCATION [Link]


Dictionary Items
Dictionary items are ordered, changeable, and does 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:

SINET EDUCATION [Link]


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

Ford

SINET EDUCATION [Link]


Note ! is Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are 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 does not have a defined order, you
cannot refer to an item by using an index.

SINET EDUCATION [Link]


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 or more items with the same key.
Duplicate values will overwrite existing values.

SINET EDUCATION [Link]


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

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

SINET EDUCATION [Link]


Dictionary Length
To determine how many items a dictionary has, use the len() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))

SINET EDUCATION [Link]


Dictionary Items - Data Types
The values in dictionary items can be of any data type:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)

{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}

SINET EDUCATION [Link]


type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

<class 'dict'>

SINET EDUCATION [Link]


Python Collections (Arrays)
There are four collection data types in the Python programming
language:
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
Dictionary is a collection which is ordered** and changeable. No
duplicate members.

SINET EDUCATION [Link]


Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x) #Mustang

SINET EDUCATION [Link]


Get the value of the "model" key using get()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("model")
print(x)
Mustang

SINET EDUCATION [Link]


Get Keys using keys() function
The keys() method will return a list of all the keys in the dictionary.
company= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
dict_keys(['brand', 'model', 'year'])

Note: 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.

SINET EDUCATION [Link]


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
car["Price"] = 120000
print(x) #after the change

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


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

SINET EDUCATION [Link]


Get Values using values()
method
The values() method will return a list of all the values in the dictionary.
Cmpny = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
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.

SINET EDUCATION [Link]


How to make a change in the original dictionary ?
How to see that the values list gets updated as well?
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])

SINET EDUCATION [Link]


Add a new item to the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])

SINET EDUCATION [Link]


The items() method will return each item in a dictionary, as tuples in a list.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

SINET EDUCATION [Link]


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
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)])
The items() method will return each item in a dictionary, as tuples in a
list.

SINET EDUCATION [Link]


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
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')])
The items() method will return each item in a dictionary, as tuples in a list.

SINET EDUCATION [Link]


Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
car= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in car :
print("Yes, 'model' is one of the keys in the car dictionary")
Yes, 'model' is one of the keys in the car dictionary

SINET EDUCATION [Link]


Change Values
You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

SINET EDUCATION [Link]


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.
Update the "year" of the car by using the update() method:

SINET EDUCATION [Link]


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

SINET EDUCATION [Link]


Add Dictionary Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

SINET EDUCATION [Link]


Remove Dictionary Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}

SINET EDUCATION [Link]


The popitem() method removes the last inserted item
(in versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}

SINET EDUCATION [Link]


The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}

SINET EDUCATION [Link]


The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{}

SINET EDUCATION [Link]


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().

SINET EDUCATION [Link]


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

SINET EDUCATION [Link]


Another way to make a copy is to use the built-in function dict().
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

SINET EDUCATION [Link]


Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},

SINET EDUCATION [Link]


"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}}

SINET EDUCATION [Link]


Create three dictionaries, then create one dictionary that will contain the
other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}

SINET EDUCATION [Link]


child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

print(myfamily)

SINET EDUCATION [Link]


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

SINET EDUCATION [Link]


Thank you

SINET EDUCATION [Link]

You might also like