Python Dictionary
Table Of Contents:
- What Is A Dictionary?
- How To Create A Python Dictionary?
- Accessing Dictionary Elements.
- Looping Through Dictionary.
- Adding Elements To Dictionary.
- Updating Values In Dictionary.
- Removing Items From Dictionary.
- Copying A Dictionary.
- Deleting A Dictionary.
(1) What Is A Dictionary?
- Dictionaries are used to store data in key:value pairs.
- Key is used to uniquely identify each value.
- Dictionary preserves the order of the elements stored.
- Dictionary do not allow duplicate elements to store.
- Dictionary is mutable in nature, that means we can add,remove or update the values of
- Dictionary without creating a new memory location.
(2) How To Create A Dictionary?
- Dictionaries are written using curly brackets { }.
- Elements of the dictionary will be Key : Value pairs separated by comma ( , ).
Example-1
dict1 = {
"Name": "Subrat",
"Roll No": 16783,
"Subject":"Math",
"Percentage":95
}
print(dict1)
Output:
{'Name': 'Subrat', 'Roll No': 16783, 'Subject': 'Math', 'Percentage': 95}
Example-2
dict2 = {
"Name": "Abhispa Pattnaik",
"Address":'Odisha,India',
"Pin":654786,
"Land Mark":'Near Bank'
}
print(dict2)
Output:
{'Name': 'Abhispa Pattnaik', 'Address': 'Odisha,India', 'Pin': 654786, 'Land Mark': 'Near Bank'}
Note:
- Here both key and values are variables. You have to write them as per the variable rules.
- In both the examples I have taken key as a String type.
(3) Accessing Dictionary Elements?
- You can access the items of a dictionary by referring to its key name, inside square brackets.
- There is also a method called get() that will give you the same result.
Example-1: Using Keys
dict1 = {
"Name": "Abhispa Pattnaik",
"Address":'Odisha,India',
"Pin":654786,
"Land Mark":'Near Bank'
}
print(dict1['Name'])
print(dict1['Address'])
print(dict1['Pin'])
print(dict1['Land Mark'])
Output:
Abhispa Pattnaik
Odisha,India
654786
Near Bank
Example-2: get() Method
dict2 = {
"Name": "Abhispa Pattnaik",
"Address":'Odisha,India',
"Pin":654786,
"Land Mark":'Near Bank'
}
print(dict2.get("Name"))
print(dict2.get("Address"))
print(dict2.get("Pin"))
print(dict2.get("Land Mark"))
Output:
Abhispa Pattnaik
Odisha,India
654786
Near Bank
(4) Looping Through A Dictionary
- You can loop through a dictionary by using a for loop.
- When looping through a dictionary, the return value are the keys of the dictionary.
- keys() method will return you all the Keys of the Dictionary.
- values() method will return you all the values of the Dictionary.
- items() method will return you both key and values of the Dictionary.
Example-1: Printing Keys Of The Dictionary
thisdict = {
"Name": "Abhispa Pattnaik",
"Address":'Odisha,India',
"Pin":654786,
"Land Mark":'Near Bank'
}
for val in thisdict:
print(val)
Output:
Name
Address
Pin
Land Mark
Note:
- Here val will contains keys of the Dictionary.
- By using key you can access the values of the Dictionary using square bracket [ ].
Example-2: Printing Values Of The Dictionary
thisdict = {
"Name": "Abhispa Pattnaik",
"Address":'Odisha,India',
"Pin":654786,
"Land Mark":'Near Bank'
}
for val in thisdict:
print(thisdict[val])
Output:
Abhispa Pattnaik
Odisha,India
654786
Near Bank
Example-3: Using keys() Method
thisdict = {
1:'Yudhishtira',
2:'Bhima',
3:'Arjuna',
4:'Nakula',
5:'Sahadeva'
}
for keys in thisdict.keys():
print(keys)
Output:
1
2
3
4
5
Example-4: Using values() Method
thisdict = {
1:'Yudhishtira',
2:'Bhima',
3:'Arjuna',
4:'Nakula',
5:'Sahadeva'
}
for values in thisdict.values():
print(values)
Output:
Yudhishtira
Bhima
Arjuna
Nakula
Sahadeva
Example-5: Using items() Method
thisdict = {
1:'Yudhishtira',
2:'Bhima',
3:'Arjuna',
4:'Nakula',
5:'Sahadeva'
}
for key, value in thisdict.items():
print('Key:',key)
print('Value:',value)
Output:
Key: 1
Value: Yudhishtira
Key: 2
Value: Bhima
Key: 3
Value: Arjuna
Key: 4
Value: Nakula
Key: 5
Value: Sahadeva
(5) Adding New Items To A Dictionary
- You can add new item by using new key name and assigning a value to it.
- update( ) method will update the original Dictionary element to a new value. If the item does not exist, the new item will be added.
- For update( ) method the argument must be a dictionary, or an iterable object with key:value pairs.
Example-1: Using key and value
thisdict = {
1:'India',
2:'USA',
3:'France',
4:'Finland',
5:'Ireland'
}
print('Before',thisdict)
thisdict[6] = 'Poland' #You Can Update By Using A New Key
print('After',thisdict)
Output:
Before {1: 'India', 2: 'USA', 3: 'France', 4: 'Finland', 5: 'Ireland'}
After {1: 'India', 2: 'USA', 3: 'France', 4: 'Finland', 5: 'Ireland', 6: 'Poland'}
Example-2: Using update() Method
thisdict = {
1:'India',
2:'USA',
3:'France',
4:'Finland',
5:'Ireland'
}
print('Before',thisdict)
thisdict.update({6:'Poland'}) #Using Update Method.
print('After',thisdict)
Output:
Before {1: 'India', 2: 'USA', 3: 'France', 4: 'Finland', 5: 'Ireland'}
After {1: 'India', 2: 'USA', 3: 'France', 4: 'Finland', 5: 'Ireland', 6: 'Poland'}
(6) Updating Values To A Dictionary
- update( ) method will update the original Dictionary element to a new value. If the item does not exist, the new item will be added.
- For update( ) method the argument must be a dictionary, or an iterable object with key:value pairs.
Example-1: Updation Using Key : Value Pair
thisdict = {
'Rank1':'Subrat',
'Rank2':'Abhipsha',
'Rank3':'Smita',
'Rank4':'Suchitra',
'Rank5':'Monalisa',
}
print('Before',thisdict)
thisdict['Rank6'] = 'Aradhna' #You Can Update By Using A New Key
print('After',thisdict)
Output:
Before {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Monalisa'}
After {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Monalisa', 'Rank6': 'Aradhna'}
Example-2: Using update( ) Method
thisdict = {
'Rank1':'Subrat',
'Rank2':'Abhipsha',
'Rank3':'Smita',
'Rank4':'Suchitra',
'Rank5':'Monalisa',
}
print('Before',thisdict)
thisdict.update({'Rank6':'Aradhna'}) #Using Update Method.
print('After',thisdict)
Output:
Before {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Monalisa'}
After {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Monalisa', 'Rank6': 'Aradhna'}
Example-3: Updating Existing Key
thisdict = {
'Rank1':'Subrat',
'Rank2':'Abhipsha',
'Rank3':'Smita',
'Rank4':'Suchitra',
'Rank5':'Monalisa',
}
print('Before',thisdict)
thisdict.update({'Rank5':'Aradhna'}) #Using Update Method.
print('After',thisdict)
Output:
Before {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Monalisa'}
After {'Rank1': 'Subrat', 'Rank2': 'Abhipsha', 'Rank3': 'Smita', 'Rank4': 'Suchitra', 'Rank5': 'Aradhna'}
Note:
- Here ‘Rank5′:’Monalisa’ has updated to ‘Rank5’: ‘Aradhna’.
- If you are updating the existing key value then, it’s value will be updated to new value.
(7) Removing Items From Dictionary.
- The pop() method removes the item with the specified key name. And return the value which is removed.
- The pop() method takes dictionary key as its argument.
- The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead).
- The del keyword removes the item with the specified key name.
- The del keyword can also delete the dictionary completely.
- The clear() method empties the dictionary.
Example-1: Using pop() Method
thisdict = {
1:'Math',
2:'Science',
3:'English',
4:'History',
5:'Geography',
6:'Economics',
}
print('Before',thisdict)
popped = thisdict.pop(4)
print(popped)
print('After',thisdict)
Output:
Before {1: 'Math', 2: 'Science', 3: 'English', 4: 'History', 5: 'Geography', 6: 'Economics'}
History
After {1: 'Math', 2: 'Science', 3: 'English', 5: 'Geography', 6: 'Economics'}
Example-2: Using popitem() Method
thisdict = {
1:'Math',
2:'Science',
3:'English',
4:'History',
5:'Geography',
6:'Economics',
}
print('Before',thisdict)
popped = thisdict.popitem()
print(popped)
print('After',thisdict)
Output:
Before {1: 'Math', 2: 'Science', 3: 'English', 4: 'History', 5: 'Geography', 6: 'Economics'}
(6, 'Economics')
After {1: 'Math', 2: 'Science', 3: 'English', 4: 'History', 5: 'Geography'}
Example-3: Using del Keyword
thisdict = {
1:'Math',
2:'Science',
3:'English',
4:'History',
5:'Geography',
6:'Economics',
}
print('Before',thisdict)
del thisdict[3] #Deleating A Specefic Key.
print('After',thisdict)
Output:
Before {1: 'Math', 2: 'Science', 3: 'English', 4: 'History', 5: 'Geography', 6: 'Economics'}
After {1: 'Math', 2: 'Science', 4: 'History', 5: 'Geography', 6: 'Economics'}
Example-4: Using clear() Method
thisdict = {
1:'Math',
2:'Science',
3:'English',
4:'History',
5:'Geography',
6:'Economics',
}
print('Before',thisdict)
thisdict.clear()
print('After',thisdict)
Output:
Before {1: 'Math', 2: 'Science', 3: 'English', 4: 'History', 5: 'Geography', 6: 'Economics'}
After {}
(8) Copying A Dictionary.
- You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
- You can use inbuilt copy() method to copy the dictionary.
Example-1
thisdict = {
'table':'chair',
'laptop':'mouse',
'paper':'pen',
'mobile':'charger',
'water':'life'
}
mydict = thisdict.copy()
print(thisdict)
print(mydict)
Output:
{'table': 'chair', 'laptop': 'mouse', 'paper': 'pen', 'mobile': 'charger', 'water': 'life'}
{'table': 'chair', 'laptop': 'mouse', 'paper': 'pen', 'mobile': 'charger', 'water': 'life'}
(9) Deleting A Dictionary.
- You can use del keyword to delete a dictionary.
Example-1
thisdict = {
2:4,
3:9,
4:16,
5:25,
6:36
}
del thisdict
print(thisdict)
Output:
NameError Traceback (most recent call last)
Input In [39], in <cell line: 11>()
1 thisdict = {
2 2:4,
3 3:9,
(...)
6 6:36
7 }
9 del thisdict
---> 11 print(thisdict)
NameError: name 'thisdict' is not defined