Open In App

Python Dictionary Methods

Last Updated : 11 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python dictionary methods is collection of Python functions that operates on Dictionary.

Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the functions provided by Python to work with dictionaries.

List of Python Dictionary Methods

Python provides several built-in methods for dictionaries that allow for efficient manipulation, access, and transformation of dictionary data. Here’s a list of some important Python dictionary methods:

Functions Name

Descriptions

clear()

Removes all items from the dictionary

copy()

Returns a shallow copy of the dictionary

fromkeys()

Creates a dictionary from the given sequence

get()

Returns the value for the given key

items()

Return the list with all dictionary keys with values

keys()

Returns a view object that displays a list of all the keys in the dictionary in order of insertion

pop()

Returns and removes the element with the given key

popitem()

Returns and removes the key-value pair from the dictionary

setdefault()

Returns the value of a key if the key is in the dictionary else inserts the key with a value to the dictionary

values()

Returns a view object containing all dictionary values, which can be accessed and iterated through efficiently

update()

Updates the dictionary with the elements from another dictionary or an iterable of key-value pairs. With this method, you can include new data or merge it with existing dictionary entries

These methods provide various functionalities for working with dictionaries in Python, making it easier to manage and manipulate data stored in key-value pairs.

Note: For more information on Python Dictionary refer to Python Dictionary Tutorial.

Built-in Dictionary Methods in Python

In Python Dictionary we have various built-in functions that provide a wide range of operations for working with dictionaries. These techniques enable efficient manipulation, access, and transformation of dictionary data.

Lets Look at some Python dictionary methods with examples:

1. Dictionary clear() Method

The clear() method in Python is a built-in method that is used to remove all the elements (key-value pairs) from a dictionary. It essentially empties the dictionary, leaving it with no key-value pairs.

Python
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)

Output
{}

2. Dictionary get() Method

In Python, the get() method is a pre-built dictionary function that enables you to obtain the value linked to a particular key in a dictionary. It is a secure method to access dictionary values without causing a KeyError if the key isn’t present.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))

Output
Ram
None

3. Dictionary items() Method

In Python, the items() method is a built-in dictionary function that retrieves a view object containing a list of tuples. Each tuple represents a key-value pair from the dictionary. This method is a convenient way to access both the keys and values of a dictionary simultaneously, and it is highly efficient.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.items())[1][0])
print(list(d.items())[1][1])

Output
Age
19

4. Dictionary keys() Method

The keys() method in Python returns a view object with dictionary keys, allowing efficient access and iteration.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.keys()))

Output
['Name', 'Age', 'Country']

5. Dictionary values() Method

The values() method in Python returns a view object containing all dictionary values, which can be accessed and iterated through efficiently.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.values()))

Output
['Ram', '19', 'India']

6. Dictionary update() Method

Python’s update() method is a built-in dictionary function that updates the key-value pairs of a dictionary using elements from another dictionary or an iterable of key-value pairs. With this method, you can include new data or merge it with existing dictionary entries.

Python
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}

d1.update(d2)
print(d1)

Output
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}

7. Dictionary pop() Method

In Python, the pop() method is a pre-existing dictionary method that removes and retrieves the value linked with a given key from a dictionary. If the key is not present in the dictionary, you can set an optional default value to be returned.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.pop('Age')
print(d)

Output
{'Name': 'Ram', 'Country': 'India'}

8. Dictionary popitem() Method

In Python, the popitem() method is a dictionary function that eliminates and returns a random (key, value) pair from the dictionary.

As opposed to the pop() method which gets rid of a particular key-value pair based on a given key, popitem() takes out and gives back a pair without requiring a key to be specified.

Python
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.popitem()
print(d)

d.popitem()
print(d)

Output
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}

FAQs on Python Dictionary Methods

Q1: What is a Python Dictionary?

In Python, a dictionary is like a container that holds an assortment of key-value pairs, It’s a fundamental way to organize data where each piece of information is known as a “Key”. The Dictionary doesn’t impose any specific order on these pairs, so you can’t rely on the sequence in which they were added.

Q2: How we can access values in a Python dictionary?

We can access values in a Python dictionary by using the keys as the index: Below is the code:

my_dict = {“name”: “Kin”, “age”: 23, “city”: “London”}

print(my_dict[“name”]) #kin

print(my_dict[“age”]) #23

print(my_dict[“city”]) #London

Q3: What happens when we try to access a key that doesn’t exist in the dictionary?

When we try to access a key that doesn’t exist in the dictionary, Python will raise a ‘KeyError’. You can use the ‘get()’ method.

Q4: How do we remove an item from a dictionary?

To remove an item (key-value pair) from a dictionary, you can use the ‘pop()’ method, specifying the key to be removed.



Similar Reads

Methods of Ordered Dictionary in Python
An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has chara
3 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
three90RightbarBannerImg