Dictionary in Python
Create a dictionary in Python
A dictionary in Python is a key-value pair of objects. Key-value pairs can be different data types. To create an empty dictionary, below is the syntax.
dict_example = {}
Let’s create a dictionary with some data.
car_models = { "Creta": 2024,
"Venue" : 2023,
"Nexon":2022
}
Print this dictionary.
Let’s check the datatype of the dictionary.
print("\nCheck Datatype")
print(type(car_models))
Data type ‘dict’ as you see refers to the class dictionary.
To print the specific value.
print(f"Creta Model : {car_models['Creta']}")
print(f"Venue Model : {car_models['Venue']}")
print(f"Nexon Model : {car_models['Nexon']}")
If you try to find the non-existent value you will get an error.
print('Figo Model',car_models['Figo'])
If you want to handle this error and print a custom message, use the get() method.
print('Figo Model',car_models.get('Figo', 'This value does not exist'))
If the Figo model doesn’t exist in the dictionary, it will print the message ‘This value does not exist‘ otherwise the value of the item and program execution continues.
Add / Append values to the dictionary
To append values to the dictionary, add new values as shown below.
car_models['Figo'] = 2025
print(car_models)
print('Figo Model',car_models['Figo'])
Removing Items from the dictionary
To remove an item from the dictionary, use the del command.
del car_models['Figo']
print('Figo Model',car_models.get('Figo', 'This value does not exist'))
Getting keys and values from the dictionary
To work with Keys and Values directly, there are methods available in Python. keys() is to get all keys and values() to get all the values of the dictionary.
print("Keys from the dictionary")
print(car_models.keys())
print("\nValues from the dictionary")
print(car_models.values())
Looping through dictionary
To loop through the dictionary, we can use the for or while loop.
# loop through dictionary.
print("\nLoop through Dictionary")
for dict in car_models:
print(dict)
We are getting values here. If you need both keys and values then you need to use the items() property to get both keys and values.
print("\nLoop though dictionary with keys and values")
for dict in car_models.items():
print(dict)
To retrieve each key and value separately, you need to use the two variables in the for loop. For example,
print("\Retrieve each key and values separately")
for key, value in car_models.items():
print(f"Key: {key} => value: {value}")
Here we are storing keys in the Key variable while values are in the value variable. (any name you can provide for variables).
Print only keys and values,
# print only keys
print("\nPrint only keys")
for key in car_models.keys():
print(f"Key: {key}")
# Print only values.
print("\nPrint only values")
for value in car_models.values():
print(f"value: {value}")