Dictionaries - zamaniamin/python GitHub Wiki
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.
Keys can be any immutable type: numbers
, strings
, booleans
, etc.
Values can be whatever you want!
Dictionaries are written with curly brackets, and have keys and values:
empty_dict = {}
empty_dict = dict()
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
The dict() Constructor
It is also possible to use the dict() constructor to make a dictionary.
person_dict = dict(name="John", age=36, country="Norway")
Dictionary Properties
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.
Duplicate values will overwrite existing values:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
Dictionary Items Data Types
The values in dictionary items can be of any data type.
car_dict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets.
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_dict["model"]
There is also a method called get()
that will give you the value
, otherwise it returns None
:
car_dict.get("model")
Dictionary Length
To determine how many items a dictionary has, use the len()
function.
len(car_dict)
Type
From Python's perspective, dictionaries are defined as objects with the data type
dict
:<class 'dict'>
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(car_dict))
Get Keys
The keys()
method will return a list of all the keys in the dictionary.
dict.keys()
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
keys = car_dict.keys()
# before the change
print(keys)
car_dict["color"] = "white"
# after the change
print(keys)
Get Values
Get a list of the values:
dict.values()
Make a change in the original dictionary, and see that the values list gets updated as well:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
values = car_dict.values()
# before the change
print(values)
car_dict["year"] = 2020
car_dict["color"] = "red"
# after the change
print(values)
Get Items
The items()
method will return each item in a dictionary, as tuples in a list.
Get a list of the key : value
pairs
dict.items()
Make a change in the original dictionary, and see that the items list gets updated as well:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_items = car_dict.items()
# before the change
print(car_items)
car_dict["year"] = 2020
car_dict["color"] = "red"
# after the change
print(car_items)
Check if Key Exists
To determine if a specified key is present in a dictionary use the in
keyword. it will only look at the keys, not the values.
Check if "model" is present in the dictionary:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in car_dict:
print("Yes, 'model' is one of the keys in the car_dict dictionary")
Change Values
You can change the value of a specific item by referring to its key name.
Change the "year" to 2018:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_dict["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.
Update the "year" of the car by using the update()
method:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_dict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_dict["color"] = "red"
Removing Items
There are several methods to remove items from a dictionary.
The pop()
method removes the item with the specified key name:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_dict.pop("model")
The popitem()
method removes the last inserted item:
car_dict.popitem()
The del
keyword removes the item with the specified key name:
del car_dict["model"]
The del
keyword can also delete the dictionary completely:
del car_dict
print(car_dict) # this will cause an error because "car_dict" no longer exists.
The clear()
method empties the dictionary:
car_dict.clear()
Loop Dictionaries
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.
Print all key names in the dictionary, one by one:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for key in car_dict:
print(key)
# You can use the `keys()` method to return the keys of a dictionary:
for key in car_dict.keys():
print(key)
Print all values in the dictionary, one by one:
for key in car_dict:
print(car_dict[key])
# You can also use the `values()` method to return values of a dictionary:
for value in car_dict.values():
print(value)
Loop through both keys and values, by using the items()
method:
for key, value in car_dict.items():
print(key, value)
last for loop
works like this:
first, second = ['a', 'b']
# like this
first = 'a'
second = 'b'
Copy
You cannot copy a dictionary simply by typing
dict2 = dict1
, because:dict2
will only be a reference todict1
, and changes made indict1
will automatically also be made indict2
.There are ways to make a copy, one way is to use the built-in Dictionary method
copy()
.
Make a copy of a dictionary with the copy()
method:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
my_dict = car_dict.copy()
Another way to make a copy is to use the built-in function dict()
:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
my_dict = dict(car_dict)
Test of dict id
dict1 = {1: 'one'}
dict2 = dict1
id(dict1)
id(dict2)
dict2[2] = 'two'
print(dict1) # output: {1:'one',2:'two'}
print(dict2) # output: {1:'one',2:'two'}
print(dict1 is dict2) # True
dict3 = dict1.copy()
print(dict3) # output: {1:'one',2:'two'}
print(dict1 is dict3) # False
print(dict1 == dict3) # True
Nested Dictionary
A dictionary can contain dictionaries, this is called nested dictionaries.
my_family = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}
# or
child1 = {
"name": "Emil",
"year": 2004
}
child2 = {
"name": "Tobias",
"year": 2007
}
child3 = {
"name": "Linus",
"year": 2011
}
my_family = {
"child1": child1,
"child2": child2,
"child3": child3
}
**
Trick
We can use two star **
to combine multiple dictionaries into a new resulting dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {**dict1, **dict2}
print(dict3)
# output: {'a':1, 'b':2, 'c':3, 'd':4}
Dict Union
Python 3.9 added the dict union operator
|
it will return a newdict
containing the items from the left and the right dicts. in the case of duplicated keys, the right side "wins".
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = dict1 | dict2
# or
dict1 |= dict2
# output: {'a':1, 'b':2, 'c':3, 'd':4}
Lambda in Dictionary
Python supports the concept of dictionary dispatch. The dictionary is a hash table of keys mapped to functions.
Here's an example using some lambdas:
function_dict = {'sum': (lambda val1, val2: x + y), 'subtract': (lambda val1, val2: x - y)}
print(function_dict['sum'](13, 4))
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
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