Updated April 14, 2023
Introduction to Python Dictionary Methods
The most widely used collection data type in python programming is definitely dict. It holds an unordered set of elements within it, but the significant element about python dict data types is that they operate as key-value pairs. So when a specific key is passed into a dictionary, the dictionary element can return the corresponding value for it. As noticed in the below example, the dictionary element will be wrapped within the curly braces.
Syntax:
{ Key: Value }
Example:
{ 'A':'Ant','B':'Bat','c':'calf','d':'doll','e':'elephant'
'f ':'flight','g':'gem','h':'hall','i':'ignite','j':'jump'}
Methods of Python Dictionary
Following are the methods of python dictionary:
Method |
Description |
Syntax |
copy() | An entire dictionary will be copied into a new dictionary |
|
update() | Helps to update an existing dictionary item | |
get() | Returns the value of the given key |
|
pop() | The element with the mentioned key will be removed |
|
values() | All the values in the given dictionary will be returned |
|
Keys() | All the keys in the given dictionary will be returned |
|
items() | Used for displaying the items of a dictionary |
|
sort() | allows sorting the dictionary items |
|
len() | Used to determine the total number of items in the dictionary |
|
Str() | For casting a dict item into a string item |
|
1. Copy()
The copy method is used for copying the contents of one dictionary to another dictionary, So this will include copying of keys and values of the first dict into another given dictionary. So every item of the current dictionary will be placed into the new one created.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
Two_wheelers = Bikes.copy()
print("All two wheelers in the market: ", Two_wheelers)
Output:
2. get()
The get() method is used to get the given key’s value in a dict variable.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
print('The second bike:',Bikes.get('Bike_2'))
Output:
3. Update()
Two key processes can be achieved by using this update() method. So first, this involves the process of revising an existing key-value pair in the dictionary, whereas the other one is the process of inserting a fresh entry into the dictionary. Every new key, value pair that has been added is affixed to the last part of the dict. likewise whilst an existing dictionary constituent is updated, it will not apply any change of position to the component, whereas only the update remains applicable only to that particular item.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
Bikes.update({'Bike_4': 'TVS'})
print("List of bikes in the market after update 1:", Bikes)
print(" ")
Bikes.update({'Bike_3': 'Hero-Honda'})
print("List of bikes in the market after update 2:", Bikes)
Output:
4. Items()
For displaying each and every key-value pair of the python dictionary, the method called items() has been used. so all the entities of a dictionary will get displayed by using the items method. At the given example, we can notice all the dictionary bikes’ elements are displayed in the execution console.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
print('All bikes:',Bikes.items())
Output:
5. keyes()
For displaying the entire set of keys in the dictionary, the keyes() method is used. So each and every key in the dict will get nicely displayed here.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
print('All bikes:',Bikes.keys())
Output:
6. sort()
For ordering or sorting the key value pairs in a dictionary, the sort method has been used. Each and every element in the dictionary gets sorted by applying this method.
Example:
Bikes={'Bike_2':'CT100','Bike_1':'HeroHonda','Bike_3':'Yamaha'}
print('All bikes:',sorted(Bikes.items()))
Output:
7. values()
The values method is used to display all the values in the dictionary.
Example:
Bikes={'Bike_1':'CT100','Bike_2':'HeroHonda','Bike_3':'Yamaha'}
print('The second bike:',Bikes.values())
Output:
8. len()
For estimating the count of total key value pairs in a dictionary data type, the len() method can be wisely used. So the count of total elements in the dictionary can be determined by means of this method. here it operates more like an encapsulated method where the dict item will be encapsulated within this len() method.
Example:
Bikes={'Bike_2':'CT100','Bike_1':'HeroHonda','Bike_3':'Yamaha'}
print('Overall number of bikes:',len(Bikes))
Output:
9. str()
For converting a dictionary into a string, the str() method can be used. This process is more of a typecasting kind of method. So it involves converting an item of one data type to a different data type. This process also involves the technique of encapsulating a dict item into a string item.
We can notice from the below-enlisted example a set of three key value pairs are specified. these three key value pairs are responsible for getting themselves cast into a string value.
Example:
Bikes={'Bike_2':'CT100','Bike_1':'HeroHonda','Bike_3':'Yamaha'}
Bikes_str = str(Bikes)
print('Format of Bikes datatype:',type(Bikes_str))
Output:
Example of Python Dictionary
Example of python dictionary are:
Code:
# dicitonary creation
Test_dict = {1:10,2:20,3:90,4:16,5:25,6:66,7:99}
# Item copy
Test_dict_copy = Test_dict.copy()
print("Newly copied dict:",Test_dict_copy)
# Item updation
Test_dict.update({'8':'800'})
print("Dict after an new insert:",Test_dict_copy)
# Items in the dict
print("Elements in the Dict:",Test_dict.items())
# item deleteion
print("Deletion of a item from the dicitionary:",Test_dict.pop(3))
print("Dictionary after the deletion:")
print(Test_dict)
print("Removal of the most arbitary item in the dicitonary:")
# arbitary item removal
print(Test_dict.popitem())
print("Dictionary after arbitary item deletion:")
print(Test_dict)
print("Removing all items from the dicitionary:")
# remove all items
Test_dict.clear()
# Output: {}
print(Test_dict)
Output:
Code Explanation: The example mentioned above engross the dictionary creation process, which is very much bizarre and involves the reach of the dictionary by means of an index oriented technique. Here the pop() method is used for deleting the elements of the dictionary. In contrast, the popitem() method is involved in deleting the most arbitrary item. On the other end, the clear() method is responsible for deleting all the items declared in the dictionary item. At first, a pop is carried out with respect to the index. Next, an undefined pop which carries out the removal of the most arbitrary item in the dict; lastly, the entire dictionary is cleaned up using the clear method.
Conclusion
Collection data types hold a significant role across all programming language standards in the market. For handling sophisticated data handling the dict(,) method of python is very much useful. Especially the dictionary component of python proffer a great space for primitive data handling in python.
Recommended Articles
We hope that this EDUCBA information on “Python Dictionary Methods” was beneficial to you. You can view EDUCBA’s recommended articles for more information.