close
The Wayback Machine - https://web.archive.org/web/20240905235616/https://www.geeksforgeeks.org/python-dictionary-get-method/
Open In App

Python Dictionary get() Method

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).

Python Dictionary get() Method Syntax:

Syntax : Dict.get(key, Value)

Parameters: 

  • key: The key name of the item you want to return the value from
  • Value: (Optional) Value to be returned if the key is not found. The default value is None.

Returns: Returns the value of the item with the specified key or the default value.

Python Dictionary get() Method Example

Python
d = {'coding': 'good', 'thinking': 'better'}
print(d.get('coding'))

Output:

good

Example 1: Python get() Method with Second Parameter

Here, In the code 4 is not in keys, so the second parameter will print “Not found”.

Python
d = {1: '001', 2: '010', 3: '011'}

print(d.get(4, "Not found"))

Output

Not found

Example 2: Python Dictionary get() method chained

The get() to check and assign in absence of value to achieve this particular task. Just returns an empty Python dict() if any key is not present.

Python
test_dict = {'Gfg' : {'is' : 'best'}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# using nested get()
# Safe access nested dictionary key
res = test_dict.get('Gfg', {}).get('is')
  
# printing result
print("The nested safely accessed value is :  " + str(res))

Output:

The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is : best

Time complexity: O(1) because it uses the get() method of dictionaries which has a constant time complexity for average and worst cases.
Auxiliary space: O(1) because it uses a constant amount of additional memory to store the dictionary and the string values. 

Python Dictionary get() Method – FAQs

What does get() do in Python dictionary?

The get() method in a Python dictionary returns the value for a specified key if the key is in the dictionary. If the key is not found, it returns a specified default value, which is None if no default value is provided.

my_dict = {'name': 'Alice', 'age': 25}

# Get value for existing key
print(my_dict.get('name')) # Output: Alice

# Get value for non-existing key with default value
print(my_dict.get('gender', 'Unknown')) # Output: Unknown

# Get value for non-existing key without default value
print(my_dict.get('gender')) # Output: None

What is get() method in list Python?

Python lists do not have a get() method. The get() method is specific to dictionaries. To access elements in a list, you use indexing.

my_list = [1, 2, 3]

# Accessing list elements using index
print(my_list[0]) # Output: 1
print(my_list[1]) # Output: 2
print(my_list[2]) # Output: 3

What is find() method in Python?

The find() method in Python is a string method that returns the lowest index of the substring if it is found in a string. If the substring is not found, it returns -1.

my_string = "Hello, world!"

# Find the index of a substring
print(my_string.find('world')) # Output: 7

# Find the index of a substring that doesn't exist
print(my_string.find('Python')) # Output: -1

What is the get value method in Python dictionary?

The get value method in a Python dictionary is get(). It retrieves the value associated with a given key, with an optional default value if the key is not found.

my_dict = {'name': 'Alice', 'age': 25}

# Using get method to retrieve value
print(my_dict.get('name')) # Output: Alice
print(my_dict.get('gender', 'Unknown')) # Output: Unknown

What is the default value of dictionary get() in Python?

The default value of the dictionary get() method in Python is None if no default value is provided.

my_dict = {'name': 'Alice', 'age': 25}

# Get value for a key with default value not specified
print(my_dict.get('gender')) # Output: None

# Get value for a key with default value specified
print(my_dict.get('gender', 'Unknown')) # Output: Unknown

These methods provide flexible ways to handle and retrieve data from Python dictionaries and strings


Previous Article
Next Article

Similar Reads

Use get() method to create a dictionary in Python from a list of elements
Prerequisites: Get() method for dictionaries in Python The naive approach for creating a dictionary from a list of items we can use the for loop. See the below example for better understanding. Example: li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a'] di ={} for ele in li: # Increase the value of key # if exists if ele in di: di[ele]= di[ele]+1 else: #
2 min read
Combine similar characters in Python using Dictionary Get() Method
Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the value of the item with the specified key. Syntax : dic
3 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Get length of dictionary in Python
To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary. Python Dict len() Syntax Syntax: len(Dict) Return: It returns an integer which is the length of the string. Name:Steve Age:30 Designation:ProgrammerBasic example of finding the length of a diction
5 min read
Python | Get key from value in Dictionary
Let's see how to get the key by value in Python Dictionary. Example: One-Liner code [GFGTABS] Python # creating a new dictionary my_dict ={"Java":100, "Python":112, "C":11} # one-liner print("One line Code Key value: ", list(my_dict.keys()) [list(my_dict.values()).index(100)]) [/GFGTABS]Output: JavaExtract Ke
7 min read
Get a dictionary from an Objects Fields
In this article, we will discuss how to get a dictionary from object's field i.e. how to get the class members in the form of a dictionary. There are two approaches to solve the above problem: By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary
2 min read
Python Dictionary fromkeys() Method
Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value. Python Dictionary fromkeys() Method Syntax: Syntax : fromkeys(seq, val) Parameters : seq : The sequence to be transformed into a dictionary.val : Initial values that need to be
3 min read
Python Dictionary setdefault() Method
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. Python Dictionary setdefault() Method Syntax: Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key - Key to be searched in the dictionary. default_value (optional) -
2 min read
Python Dictionary popitem() method
Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple. Python Dictionary popitem() Method Syntax: Syntax : dict.popitem() Parameters : None Returns : A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary. Note: popitem() method return
2 min read
Python Dictionary pop() Method
Python dictionary pop() method removes and returns the specified element from the dictionary. Example: C/C++ Code # inializing dictionary student student = {"rahul":7, "Aditya":1, "Shubham":4} # priting original dictionary print(student) # using dictionary pop suspended = student.pop("rahul") # checking key o
4 min read
Python Dictionary items() method
As of Python 3.7, dictionaries are ordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair.In Python Dictionary, items() are the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: This metho
2 min read
Python Dictionary keys() method
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Syntax: dict.keys() Parameters: There are no parameters. Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary. Method 1
4 min read
Python Dictionary update() method
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. Example: Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'Geeks'}Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'For', 'C
5 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a GET request. How to get GET request values in Djan
2 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
NumPy who() Method | Print Arrays in Dictionary
The who() function of the NumPy library prints the NumPy ndarray in the given dictionary of the current module. If no dictionary is passed in or vardict is None then it prints NumPy arrays in the globals() dictionary. Example C/C++ Code import numpy as np # dictionary containing numpy ndarrays gfg = {'arr_1': np.arange(3), 'arr_2': np.arange(6), 'n
1 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
GET method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make GET request to a specified URL using requests.GET() method. Before checking out GET method, let's figure out what a GET request is - GET Http Method The GET method is used to retrieve information from
2 min read
Navigating links using get method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python
2 min read
Python program to convert XML to Dictionary
In this article, we will discuss how to convert an XML to a dictionary using Python. Modules Usedxmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module. Syntax: pip install xmltodict pprint: The pprint module provides a capability to “pretty
2 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Output of Python Programs | Set 24 (Dictionary)
Prerequisite : Python-Dictionary 1. What will be the output? dictionary = {"geek":10, "for":45, "geeks": 90} print("geek" in dictionary) Options: 10 False True Error Output: 3. True Explanation: in is used to check the key exist in dictionary or not. 2. What will be the output? dictionary ={1:"geek"
2 min read
Python Dictionary to find mirror characters in a string
Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We hav
2 min read
Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe have existing solution for this problem please refer
3 min read
Article Tags :
Practice Tags :