The Wayback Machine - https://web.archive.org/web/20240823053146/https://www.geeksforgeeks.org/python-dictionary-setdefault-method/
Open In App

Python Dictionary setdefault() Method

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

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) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.

Returns: 

  • Value of the key if it is in the dictionary. 
  • None if key is not in the dictionary and default_value is not specified. 
  • default_value if key is not in the dictionary and default_value is specified.

Python Dictionary setdefault() Method Example:

Python3




d = {'a': 97, 'b': 98, 'c': 99, 'd': 100}
# space key added using setdefault() method
d.setdefault(' ', 32)
print(d)


Output:

{'a': 97, 'b': 98, 'c': 99, 'd': 100, ' ': 32}

Example 1: Using Python Dictionary setdefault() Method when key already existing in dictionary

If we use Python Dictionary setdefault() method on any existing key of a dictionary, it’ll return the value of the existing key, but will not modify the dictionary key.

Python3




d = {'a': 97, 'b': 98}
print("setdefault() returned:", d.setdefault('b', 99))
print("After using setdefault():", d)


Output: 

setdefault() returned: 98
After using setdefault(): {'a': 97, 'b': 98}

Example 2: Using Python Dictionary setdefault() Method when key not existing in dictionary

If we use setdefault() method on any non-existing key of a dictionary, it’ll return the new value added and update the dictionary with the key, value pair.

Python3




Dictionary1 = { 'A': 'Geeks', 'B': 'For'}
print("Dictionary before using setdefault():", Dictionary1)
  
# using setdefault() when key is non-existing
ret_value = Dictionary1.setdefault('C', "Geeks")
print("Return value of setdefault():", ret_value)
  
print("Dictionary after using setdefault():", Dictionary1)


Output: 

Dictionary before using setdefault(): {'A': 'Geeks', 'B': 'For'}
Return value of setdefault(): Geeks
Dictionary after using setdefault(): {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}


Previous Article
Next Article

Similar Reads

wxPython - SetDefault() function in wx.Button
In this article we are going to learn about SetDefault() function associated with the wx.Button class of wxPython. This sets the button to be the default item in its top-level window (e.g. the panel or the dialog box containing it). As normal, pressing return causes the default button to be depressed when the return key is pressed. Syntax: wx.Butto
1 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
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 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
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 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 get() Method
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 fromValue: (Optional) Value to be retu
4 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
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
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
Python Dictionary clear()
The clear() method removes all items from the dictionary. Syntax: dict.clear() Parameters: The clear() method doesn't take any parameters. Returns: The clear() method doesn't return any value. Parameters: The clear() method take O(n) time. Examples: Input : d = {1: "geeks", 2: "for"} d.clear() Output : d = {} Error: As we are not passing any parame
2 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() method Syntax: dict.copy() Return: This method does
3 min read
Python dictionary values()
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get "dict_values object". It must be cast to obtain the actual list. Python Dictionary values() Method Syntax Syntax: dictionary_name.values(
2 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
3 min read
Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary. Example: Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] Output: 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2 Explanation: Here 1 occurs 5 times, 2 occurs 4 times and so on... The problem can be s
4 min read
three90RightbarBannerImg