Python Dictionaries (Full Explained)
In Python, Dictionaries allows us to store data in key: value pairs. Dictionary is one of the 4 built-in data types in python, the other 3 are Lists, Tuples and Sets.
Dictionaries are mutable and ordered collection of key-value pairs. They can also contain elements of different Data type. Here is an example of how you can create a dictionary in Python.
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} print(fruit_dict) #Outputs: {'Mango': 100, 'Apple': 150, 'Banana': 80, 'Orange': 'Fifty'}
In an above example, the dictionary (fruit_dict
) contains four key-value pairs. The keys are "Mango"
, "Apple"
, "Banana"
and "Orange"
, and the corresponding values are 100
, 150
, 80
and "Fifty"
.
You can also access the values in a dictionary by using the keys as the index. Here is an example:
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} print (fruit_dict["Mango"]) #Outputs: 100 print (fruit_dict["Orange"]) #Outputs: Fifty
Change Dictionary Items
In Python, we can change the value of a specific item by simply referring to it’s index name. Here is an example:
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} #changing the dictionary item fruit_dict["Banana"] = 160 print (fruit_dict) #Outputs: {'Mango': 100, 'Apple': 150, 'Banana': 160, 'Orange': 'Fifty'}
Add Item to a Dictionary
In Python, we can add new items to a dictionary by simply using a new index key and assigning any value to it. Here is an example:
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} #Adding new item to a dictionary fruit_dict["Grapes"] = 120 print (fruit_dict) #Outputs: {'Mango': 100, 'Apple': 150, 'Banana': 80, 'Orange': 'Fifty', 'Grapes': 120}
Remove Item from a Dictionary
In Python, we can remove an item from a dictionary by various ways. But most of the programmers use pop()
method. Below in an example let’s write a code to remove an item from a dictionary.
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} #Removing item from a dictionary fruit_dict.pop("Orange") print(fruit_dict)
Check if a Key is Present in a Dictionary
To check if an key is present in a dictionary or not we can use the python membership operator. It returns True if a Key is present in a Dictionary, otherwise False. Here is an example:
Example
fruit_dict = {"Mango": 100, "Apple": 150, "Banana": 80, "Orange": "Fifty"} #Check if a key is present in a dictionary print("Mango" in fruit_dict) #Outputs: True print ("Grapes" in fruit_dict) #Outputs: False print (100 in fruit_dict) #Outputs: False
Remember that we can only check if a key is present in a dictionary, not a value. That is why it returns False when we try to check the value of Mango key (100).
Share This Post!