Python - Dictionary
A Dictionary is a type of data container in Python which is used to store multiple data in one variable. It contains data in key-value pair and can contain elements of different data types. Elements in a dictionary are unordered and hence it is not possible to access dictionary's element using index number. Dictionary's keys are immutable and hence not changeable. Additionally, it does not allow multiple elements with same key (no duplicate keys).
Create Dictionary
A dictionary can be created by separating it's elements by comma , and enclosing with curly bracket { }. Additionally, it can also be created using dict() function.
#Dictionary with multiple datatypes Info = { "name": "John", "age": 25, "city": "London" } print(Info) #Creating dictionary with constructor Info = dict(name="Marry", age=20, city="Newyork") print(Info)
The output of the above code will be:
{'name': 'John', 'age': 25, 'city': 'London'} {'name': 'Marry', 'age': 20, 'city': 'Newyork'}
Access element of a Dictionary
An element of a dictionary can be accessed using key enclosed by square brackets [ ]. The same can also be achieved using get() method.
Info = { "name": "John", "age": 25, "city": "London" } print(Info["city"]) print(Info.get("name"))
The above code will give the following output:
London John
Modify values in Dictionary
To modify value, assign new value using key.
Info = { "name": "John", "age": 25, "city": "London" } Info["city"] = "Paris" print(Info)
The above code will give the following output:
{'name': 'John', 'age': 25, 'city': 'Paris'}
Dictionary Length
The len() function can be used to find out total number of key-value pairs in the dictionary.
Info = { "name": "John", "age": 25, "city": "London" } print(len(Info))
The output of the above code will be:
3
Loop over Dictionary's keys
This method can be used to access dictionary's keys one by one.
Info = { "name": "John", "age": 25, "city": "London" } for x in Info: print(x)
The output of the above code will be:
name age city
Loop over Dictionary's values
This method can be used to access dictionary's values one by one.
Info = { "name": "John", "age": 25, "city": "London" } #first method for x in Info: print(Info[x]) print() #second method for x in Info.values(): print(x)
Each method gives the same result. The output of the above code will be:
John 25 London John 25 London
Check a Key in the Dictionary
The in keyword can be used to check whether a specified key is present in the dictionary or not.
Info = { "name": "John", "age": 25, "city": "London" } if "lastname" in Info: print("Yes, 'lastname' is a key in the dictionary.") else: print("No, 'lastname' is not a key in the dictionary.")
The above code will give the following output:
No, 'lastname' is not a key in the dictionary.
Add elements in Dictionary
This can be achieved by assigning values to new index key.
Info = { "name": "John", "age": 25, "city": "London" } Info["gender"] = "Male" print(Info)
The output of the above code will be:
{'name': 'John', 'age': 25, 'city': 'London', 'gender': 'Male'}
Delete elements of a Dictionary
There are number of ways to delete elements from a dictionary:
- pop() - deletes specified key and it's value of the dictionary.
- popitem() - deletes last key-value pair of the dictionary. Please note that dictionary is an unordered data container, hence last key-value pair is not defined.
- clear() - deletes all key-value pairs of the dictionary.
- del - deletes a key-value pair of a dictionary. can be used to delete the dictionary itself.
The example below describes how to use pop() and popitem() methods of a dictionary.
Info = { "name": "John", "age": 25, "city": "London" } Info.pop("city") print(Info) Info = { "name": "John", "age": 25, "city": "London" } Info.popitem() print(Info)
The above code will give the following output:
{'name': 'John', 'age': 25} {'age': 25, 'city': 'London'}
The example below describes how to use clear() and del methods of a dictionary.
Info = { "name": "John", "age": 25, "city": "London" } Info.clear() print(Info) Info = { "name": "John", "age": 25, "city": "London" } del Info["city"] print(Info) del Info print(Info)
The above code will give the following output:
{} {'name': 'John', 'age': 25} Traceback (most recent call last): File "Main.py", line 17, in <module> print(Info) NameError: name 'Info' is not defined
Copy Dictionary
The copy of a dictionary can be created using either = operator or copy() method.
- = operator: Using dict2 = dict1, a reference of dict1 can be created into dict2. Any change to dict1 will be reflected in dict2 also.
- copy(): This will create an independent copy of a dictionary.
Info = { "name": "John", "age": 25, "city": "London" } Info_1 = Info Info_2 = Info.copy() # Info_1 dictionary is a reference of Info print(Info_1) # Info_2 dictionary is a copy of Info print(Info_2,"\n") #deletes city key from the dictionary Info.pop("city") # displaying result after operation print(Info_1) print(Info_2)
The output of the above code will be:
{'name': 'John', 'age': 25, 'city': 'London'} {'name': 'John', 'age': 25, 'city': 'London'} {'name': 'John', 'age': 25} {'name': 'John', 'age': 25, 'city': 'London'}