Dictionaries#
A dictionary is a collection of unordered, modifiable (mutable) paired (key: value) data type.
Creating a Dictionary#
To create a dictionary we use curly brackets, {}
or the dict()
built-in function.
empty_dict = {}
empty_dict
{}
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
person
{'first_name': 'Aurora',
'last_name': 'Luna',
'age': 6,
'country': 'Indonesia',
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {'street': 'Jl. Jalan', 'zipcode': '123456'}}
The dictionary above shows that a value could be any data types: string, boolean, list, tuple, set or a dictionary.
Dictionary Length#
It checks the number of ‘key: value’ pairs in the dictionary.
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
len(d)
4
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
len(person)
6
Accessing Dictionary Items#
We can access Dictionary items by referring to its key name.
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
print(d["key1"])
print(d["key4"])
value1
value4
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
print(person["first_name"])
print(person["country"])
print(person["skills"])
print(person["skills"][0])
print(person["address"]["street"]) # Space street
# print(person['city']) # Running this will raise KeyError: 'city'
Aurora
Indonesia
['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
JavaScript
Jl. Jalan
Accessing an item by key name raises an error if the key does not exist. To avoid this error first we have to check if a key exist or we can use the get()
method. The get()
method returns None
, which is a NoneType
object data type, if the key does not exist.
print(person.get("first_name"))
print(person.get("country"))
print(person.get("skills"))
print(person.get("city"))
Aurora
Indonesia
['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
None
Adding Items to a Dictionary#
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d["key5"] = "value5"
d
{'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4',
'key5': 'value5'}
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
person["job_title"] = "Student"
person["skills"].append("TensorFlow")
person
{'first_name': 'Aurora',
'last_name': 'Luna',
'age': 6,
'country': 'Indonesia',
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python', 'TensorFlow'],
'address': {'street': 'Jl. Jalan', 'zipcode': '123456'},
'job_title': 'Student'}
Modifying Items in a Dictionary#
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d["key1"] = "value-one"
d
{'key1': 'value-one', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
person["last_name"] = "Wulan"
person["country"] = "New Zealand"
person
{'first_name': 'Aurora',
'last_name': 'Wulan',
'age': 6,
'country': 'New Zealand',
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {'street': 'Jl. Jalan', 'zipcode': '123456'}}
Checking Keys in a Dictionary#
We use the in
operator to check if a key exist in a dictionary.
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
print("key2" in d)
print("key5" in d)
True
False
Removing Key and Value Pairs from a Dictionary#
pop(key)
: removes the item with the specified key namepopitem()
: removes the last itemdel
: removes an item with specified key name
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d.pop("key1")
d
{'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d.popitem()
('key4', 'value4')
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
del d["key2"]
d
{'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
person.pop("address")
person.popitem()
del person["country"]
person
{'first_name': 'Aurora', 'last_name': 'Luna', 'age': 6}
Changing Dictionary to a List of Items#
The items()
method changes dictionary to a list of tuples.
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d.items()
dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])
person = {
"first_name": "Aurora",
"last_name": "Luna",
"age": 6,
"country": "Indonesia",
"skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
"address": {"street": "Jl. Jalan", "zipcode": "123456"},
}
person.items()
dict_items([('first_name', 'Aurora'), ('last_name', 'Luna'), ('age', 6), ('country', 'Indonesia'), ('skills', ['JavaScript', 'React', 'Node', 'MongoDB', 'Python']), ('address', {'street': 'Jl. Jalan', 'zipcode': '123456'})])
Clearing a Dictionary#
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
print(d.clear())
None
Deleting a Dictionary#
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
del d
Copy a Dictionary#
We can copy a dictionary using a copy()
method. Using copy we can avoid mutation of the original dictionary.
d1 = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
d2 = d1.copy()
d2
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
Getting Dictionary Keys as a List#
The keys()
method gives us all the keys of a a dictionary as a list.
d = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
keys = d.keys()
keys
dict_keys(['key1', 'key2', 'key3', 'key4'])
Getting Dictionary Values as a List#
The values()
method gives us all the values of a a dictionary as a list.
dct = {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
values = dct.values()
values
dict_values(['value1', 'value2', 'value3', 'value4'])