1. What is a Dictionary? Creating a Dictionary in Python
A Dictionary Data Structure in Python is used to store data in the form of keys and values. The elements in the Dictionary are ordered, changeable and do not allow 2 elements with the same key. The key and value pairs in the Dictionary are declared within curly braces {}. The values in the Dictionary can have any data type.
# empty dictionary
my_dict = {}
print(my_dict)
# dictionary with integer keys
my_dict = {
1: 'apple',
2: 'banana',
3: 'lemon'
}
print(my_dict)
# dictionary with mixed keys
my_dict = {
"name": "John",
1: [2, 3, 4],
2: "12A1"
}
print(my_dict)
# dictionary with mixed values
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1",
"subject": ["math", "literature", "english"]
}
print(my_dict)
# using dict() to create dictionary
my_dict = dict({1: 'apple', 2: 'banana', 3: 'lemon'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'banana'), (3, 'lemon')])
print(my_dict)
Output
{}
{1: 'apple', 2: 'banana', 3: 'lemon'}
{'name': 'John', 1: [2, 3, 4], 2: '12A1'}
{'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'subject': ['math', 'literature', 'english']}
{1: 'apple', 2: 'banana', 3: 'lemon'}
{1: 'apple', 2: 'banana', 3: 'lemon'}
Do not allow 2 elements with the same key in Dictionary
The Dictionary will get the latest value of the duplicate keys for that key.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1",
"class": "IT02"
}
print(my_dict)
Output
{'name': 'John', 'yearofbirth': 2000, 'class': 'IT02'}
Number of elements in Dictionary
Use the len()
function to return the number of elements in the Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
print("Number of items in my_dict:", len(my_dict))
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1",
"class": "IT02"
}
print("Number of items in my_dict:", len(my_dict))
Output
Number of items in my_dict: 3
Number of items in my_dict: 3
2. Accessing elements in Dictionary
We can access elements in the Dictionary by using the key in square brackets []. Additionally, we can also use the get()
method.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
print("Get value of 'class' key using []:", my_dict["class"])
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
print("Get value of 'class' key using get():", my_dict.get("class"))
Output
Get value of 'class' key using []: 12A1
Get value of 'class' key using get(): 12A1
2.1. Get all keys in Dictionary
The keys()
method returns a list of all keys in the Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
all_keys = my_dict.keys()
print("All keys in my_dict:", all_keys)
Output
All keys in my_dict: dict_keys(['name', 'yearofbirth', 'class'])
2.2. Get all values in Dictionary
The values()
method returns a list of all values in the Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
all_values = my_dict.values()
print("All values in my_dict:", all_values)
Output
All values in my_dict: dict_values(['John', 2000, '12A1'])
2.3. Get all elements in Dictionary
The items()
method returns each element in the Dictionary as a tuple in a list.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
all_items = my_dict.items()
print("All items in my_dict:", all_items)
Output
All items in my_dict: dict_items([('name', 'John'), ('yearofbirth', 2000), ('class', '12A1')])
2.4. Check if a key exists in the Dictionary Data Structure in Python
Use the keyword in to determine if a key exists in the Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
# check yearofbirth key
if "yearofbirth" in my_dict:
print("'yearofbirth' is one of the keys in the my_dict dictionary")
else:
print("'yearofbirth' isnot one of the keys in the my_dict dictionary")
# check subject key
if "subject" in my_dict:
print("'subject' is one of the keys in the my_dict dictionary")
else:
print("'subject' isnot one of the keys in the my_dict dictionary")
Output
'yearofbirth' is one of the keys in the my_dict dictionary
'subject' isnot one of the keys in the my_dict dictionary
3. Adding, Removing, and Changing Elements in the Dictionary
3.1. Adding elements to the Dictionary Data Structure in Python
To add an element to the Dictionary, declare a new key and assign a value to it.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict["math"] = 9.5
print("Add an item to my_dict:", my_dict)
Output
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5}
Python supports the update()
function to add the elements of one Dictionary to another Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict.update({"math": 9.5, "english": 9.9})
print("Add an item to my_dict:", my_dict)
Output
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 9.9}
3.2. Removing elements from the Dictionary Data Structure in Python
Using the pop() function
The pop()
function removes an element in the Dictionary with a predetermined key.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict.pop("class")
print("Remove an item of my_dict using pop():", my_dict)
Output
Remove an item of my_dict using pop(): {'name': 'John', 'yearofbirth': 2000}
Using the popitem() function
The popitem()
function removes the last element added to the Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict.popitem()
print("Remove an item of my_dict using popitem():", my_dict)
my_dict["class"] = "12A2"
print("Add an item to my_dict:", my_dict)
my_dict.popitem()
print("Remove an item of my_dict using popitem():", my_dict)
Output
Remove an item of my_dict using popitem(): {'name': 'John', 'yearofbirth': 2000}
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A2'}
Remove an item of my_dict using popitem(): {'name': 'John', 'yearofbirth': 2000}
Using the clear() function
The clear()
function removes all elements in the Dictionary to make it an empty Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
print("my_dict:", my_dict)
my_dict.clear()
print("Clear my_dict:", my_dict)
Output
my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}
Clear my_dict: {}
Using the del keyword
The del keyword will remove all elements in the Dictionary and also delete the reference variable to that Dictionary.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
print("my_dict:", my_dict)
del my_dict
# NameError: name 'my_dict' is not defined
#print("my_dict:", my_dict)
3.3. Changing elements in the Dictionary Data Structure in Python
We can change the value of a key in the Dictionary by reassigning the value to that key.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict["class"] = "1A2"
print("Change an item of my_dict:", my_dict)
Output
Change an item of my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '1A2'}
To change the value of a key in the Dictionary, use the update()
function with the existing key and the new value as arguments.
my_dict = {
"name": "John",
"yearofbirth": 2000,
"class": "12A1"
}
my_dict.update({"class": "1A2"})
print("Change an item of my_dict using update():", my_dict)
Output
Change an item of my_dict using update(): {'name': 'John', 'yearofbirth': 2000, 'class': '1A2'}