14.python_dictionaries_and_its_methods
14.python_dictionaries_and_its_methods
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
In [1]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ford
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
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created
Dictionary Length
To determine how many items a dictionary has, use the len() function
Example
Print the number of items in the dictionary
In [3]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
print(thisdict)
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 [7]: 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 [8]: 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 [9]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
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 [10]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
Get Values
The values() method will return a list of all the values in the dictionary
Example
Get a list of the values
In [11]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
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 [12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["year"] = 2020
Example
Add a new item to the original dictionary, and see that the values list gets
updated as well
In [13]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["color"] = "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 [14]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x)
x = car.items()
car["year"] = 2020
Example
Add a new item to the original dictionary, and see that the items list gets
updated as well
In [16]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["color"] = "red"
Change Values
You can change the value of a specific item by referring to its key name
Example
Change the "year" to 2018
In [1]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it
Example
In [2]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries
Example
Create a dictionary that contain three dictionaries
In [4]: myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
print(myfamily["child2"]["name"])
Tobias
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries
1.clear()
The clear() method removes all the elements from a dictionary
Syntax - The dictionary.clear()
No parameters
Example
Remove all elements from the car list
In [7]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
{}
2.copy()
The copy() method returns a copy of the specified dictionary
Syntax - The dictionary.copy()
No parameters
Example
Copy the car dictionary
In [8]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
3.fromkeys()
The fromkeys() method returns a dictionary with the specified keys and the
specified value
Syntax - The dict.fromkeys(keys, value)
keys - Required. An iterable specifying the keys of the new dictionary
value - Optional. The value for all keys. Default value is None
Example
Create a dictionary with 3 keys, all with the value 0
In [9]: x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Example
Same example as above, but without specifying the value
In [10]: x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)
4.pop()
The pop() method removes the specified item from the dictionary
The value of the removed item is the return value of the pop() method, see
example below
Syntax - The dictionary.pop(keyname, defaultvalue)
keyname - Required. The keyname of the item you want to remove
defaultvalue - Optional. A value to return if the specified key do not exist.
If this parameter is not specified, and the no item with the specified key is found, an
error is raised
Example
Remove "model" from the dictionary
In [11]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Example
The value of the removed item is the return value of the pop() method
In [12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.pop("model")
print(x)
Mustang
5.popitem()
The popitem() method removes the item that was last inserted into the
dictionary. In versions before 3.7, the popitem() method removes a random item
The removed item is the return value of the popitem() method, as a tuple, see
example below
Syntax - The dictionary.popitem()
No parameters
Example
Remove the last item from the dictionary
In [13]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
x = car.popitem()
print(x)
('year', 1964)
6.setdefault()
The setdefault() method returns the value of the item with the specified key
If the key does not exist, insert the key, with the specified value, see example
below
Syntax - The dictionary.setdefault(keyname, value)
keyname - Required. The keyname of the item you want to return the value
from
value - Optional.If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's value Default value None
Example
Get the value of the "model" item
In [ ]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Example
Get the value of the "color" item, if the "color" item does not exist, insert
"color" with the value "white"
In [16]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color", "white")
print(car)
7.update()
The update() method inserts the specified items to the dictionary
The specified items can be a dictionary, or an iterable object with key value pairs
Syntax - The dictionary.update(iterable)
iterable A dictionary or an iterable object with key value pairs, that will be
inserted to the dictionary
Example
Insert an item to the dictionary
In [17]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)