Python Dictionary Methods

Rumman Ansari   Software Engineer   2023-06-03   144 Share
☰ Table of Contents

Table of Content:


Python Dictionary Methods

Sr. No. Method Description Example
1 clear() Removes all the elements from the dictionary my_dict = {'name': 'John', 'age': 25}
my_dict.clear()
print(my_dict)
Output: {}
2 copy() Returns a copy of the dictionary my_dict = {'name': 'John', 'age': 25}
new_dict = my_dict.copy()
print(new_dict)
Output: {'name': 'John', 'age': 25}
3 fromkeys() Returns a dictionary with the specified keys and value keys = ['name', 'age']
value = 'Unknown'
my_dict = dict.fromkeys(keys, value)
print(my_dict)
Output: {'name': 'Unknown', 'age': 'Unknown'}
4 get() Returns the value of the specified key my_dict = {'name': 'John', 'age': 25}
value = my_dict.get('name')
print(value)
Output: 'John'
5 items() Returns a list containing a tuple for each key-value pair my_dict = {'name': 'John', 'age': 25}
items = my_dict.items()
print(items)
Output: [('name', 'John'), ('age', 25)]
6 keys() Returns a list containing the dictionary's keys my_dict = {'name': 'John', 'age': 25}
keys = my_dict.keys()
print(keys)
Output: ['name', 'age']
7 pop() Removes the element with the specified key my_dict = {'name': 'John', 'age': 25}
value = my_dict.pop('age')
print(value)
Output: 25
8 popitem() Removes the last inserted key-value pair my_dict = {'name': 'John', 'age': 25}
item = my_dict.popitem()
print(item)
Output: ('age', 25)
9 setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value my_dict = {'name': 'John'}
value = my_dict.setdefault('age', 25)
print(value)
Output: 25
10 update() Updates the dictionary with the specified key-value pairs my_dict = {'name': 'John'}
my_dict.update({'age': 25})
print(my_dict)
Output: {'name': 'John', 'age': 25}
11 values() Returns a list of all the values in the dictionary my_dict = {'name': 'John', 'age': 25}
values = my_dict.values()
print(values)
Output: ['John', 25]

I hope this helps! Let me know if you have any more questions.