Python Dictionary Methods | Dictionary Functions - Scientech Easy (2023)

In this tutorial, we will discuss Python dictionary methods and built-in functions with the help of examples. Python language provides several methods to work with a dictionary.

The list of all dictionary methods are as follows:

  • clear()
  • copy()
  • fromkeys()
  • get()
  • items()
  • keys()
  • values()
  • pop()
  • popitem()
  • setdefault()
  • update()

Let’s understand each dictionary method with syntax and various examples.

Dictionary Methods in Python

1. clear():

This method clears all the elements from the dictionary. The general syntax to call this method is as:


This method does not take any argument and not return anything.

Example 1:

# Python program to clear a dictionary.my_dict = {1: "One", 2: "Two", 3: "Three", 4: "Four"}# Call clear() method to remove all elements from a dictionary.my_dict.clear()print(my_dict)
Output: {}

2. copy():

This method returns a copy of the dictionary. It creates a shallow copy of a dictionary where every key-value pair is duplicate. The copy() method allows us to modify the dictionary copy without modifying the original dictionary.

The general syntax to declare a copy() method is as:

(Video) An Interesting approach to learn Python


In the above syntax, dict is the name of a dictionary. This method does not take any parameter.

Example 2:

# Python program to copy a dictionary.my_dict = {1: "Apple", 2: "Guava", 3: "Banana", 4: "Orange"}print("Original dictionary: ")print(my_dict)# Call copy() method to create a copy of my_dict().my_dict2 = my_dict.copy()print("Copy dictionary: ")print(my_dict2)# Modifying the dictionary copy.my_dict2[2] = "Mango"# Displaying after modifying.print("After modifying, original dictionary: ")print(my_dict)print("After modifying, Copy dictionary: ")print(my_dict2)
Output: Original dictionary: {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'} Copy dictionary: {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'} After modifying, original dictionary: {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'} After modifying, Copy dictionary: {1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange'}

In this example, we have created a dictionary of four elements. Then, we have created a copy of the original dictionary using copy() method provided by Python.

This dictionary copy is a new file which does not depend on the original dictionary from which it was produced. Thence, any changes we make to the new dictionary will have no effect at all on the original dictionary.

3. keys():

This method returns a new view or list of dictionary keys. The general syntax to define this method is as below:


Example 3:

# Python program to get a list of a dictionary keys.my_dict = {1: "Apple", 2: "Guava", 3: "Banana", 4: "Orange"}# Calling keys() function to get the keys of dictionary.dic_keys = my_dict.keys()print("Dictionary keys: ")print(dic_keys)
Output: Dictionary keys: dict_keys([1, 2, 3, 4])

4. fromkeys():

This method takes a sequence of elements and uses them as keys to construct a fresh dictionary. The basic syntax to define fromkeys() method is as below:

dict.fromkeys(seq[, value])

In the above syntax, dict is the name of a dictionary. This method takes two parameters, as:

(Video) Office Automation Part 1 - Sorting Emails with Tensorflow and Word-Embedded Vectors

  • seq: It represents the list of values for creating keys for the dictionary.
  • value: It represents optional value to be set with each key. If you do not set any value, Python will set “None” by default.

Example 4:

# Python program to create a dictionary by taking a sequence of values as keys.# Creating a list of keys.my_keys = [1, 2, 3, 4]# Calling fromkeys() function to create a dictionary with my_keys and value as "Mahika".new_dict = dict.fromkeys(my_keys, "Mahika")print("Dictionary: ", new_dict)
Output: Dictionary: {1: 'Mahika', 2: 'Mahika', 3: 'Mahika', 4: 'Mahika'}

5. get():

This method returns the value of a dictionary keys. It will return None if the key is not present in the dictionary. The general syntax to declare get() method is as:

dict.get(key, default = None)

Example 5:

# Python program to get the value of each dictionary key.my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}# Call get() method to get the value of first key.dict_value1 = my_dict.get(1)print(dict_value1)# Getting the value of second key.dict_value2 = my_dict.get(2)print(dict_value2)
Output: Mahika Ivaan

6. items():

This method returns a list of key-value pairs in tuple from the dictionary. The basic syntax to define this method is as:


Example 6:

# Python program to get a list of dictionary elements.my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}# Call items() method to get the dictionary elements in tuple form.dict = my_dict.items()print(dict)
Output: dict_items([(1, 'Mahika'), (2, 'Ivaan'), (3, 'Mark'), (4, 'Bob')])

7. pop():

This method removes a specific element (or a key: value pair) from a dictionary whose key is specified as its argument. The general syntax to define pop() method is as:


In this syntax, dict is the name of a dictionary. The pop() method takes an argument as key and returns the value of that key.

Example 7:

(Video) 26. Prediction by partial matching, PPM.

# Python program to remove a specific element from a dictionary.my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}print("Original dictionary: ")print(my_dict)# Call pop() method to remove an element form a dictionary.removed_value = my_dict.pop(3)print("Dictionary after removing an element: ")print(my_dict)print("Removed value of key: ", removed_value)
Output: Original dictionary: {1: 'Mahika', 2: 'Ivaan', 3: 'Mark', 4: 'Bob'} Dictionary after removing an element: {1: 'Mahika', 2: 'Ivaan', 4: 'Bob'} Removed value of key: Mark

8. popitem():

This method removes a random element or key-value pair from a dictionary. The basic form of this method is as:


The popitem() method takes no argument and returns an arbitrary key-value pair from the dictionary.

Example 8:

# Python program to remove a random element from a dictionary.my_dict = {"One": 1, "Two": 2, "Three": 3, "Four": 4}print("Original dictionary: ")print(my_dict)# Call popitem() method to remove a random element form a dictionary.removed_element = my_dict.popitem()print("Dictionary after removing a random element: ")print(my_dict)print("Removed element: ", removed_element)
Output: Original dictionary: {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4} Dictionary after removing a random element: {'One': 1, 'Two': 2, 'Three': 3} Removed element: ('Four', 4)

9. setdefault():

This method is used to search for a specified key in a dictionary. It returns the value of the key if found. If not, it returns the specified default value. The basic syntax for using this method is:

dict.setdefault(key, default = None)

Example 9:

# Python program to search am element from a dictionary.my_dict = {'a': "apple", 'b': "boy", 'c': "cat", 'd': "dog"}# Call setdefault() method to search an element based on a specified key form a dictionary.result = my_dict.setdefault('c', None)print(result)
Output: cat

10. update():

This method is used to update a dictionary with a set of key-value pairs from another dictionary. It merges the key-value pairs of one dictionary into another as well as overwrites the values of the other dictionary to the values of the current dictionary if a common key() exists.

The general syntax to declare this method is as:


In this syntax, dict1 and dict2 are names of two dictionaries.

Example 10:

# Python program to merge a dictionary into another dictionary.my_dict1 = {"Name": "Mahika", "Age": 17, "Gender": "Female"}my_dict2 = {"scName": "RSVM", "City": "Dhanbad"}# Merging key-value pairs of my_dict2 into my_dict1.my_dict1.update(my_dict2)print(my_dict1)
Output: {'Name': 'Mahika', 'Age': 17, 'Gender': 'Female', 'scName': 'RSVM', 'City': 'Dhanbad'}

11. values():

This method is used to acquire a list of dictionary values. The basic syntax of using this method is as:


The values() method does not accept anything but returns a list of value available in the dictionary.

Example 11:

# Python program to get a list of value available in the dictionary.my_dict = {"Name": "Mahika", "Age": 17, "Gender": "Female"}# Call values() method to get a list of dictionary values.dict_values = my_dict.values()print("List of dictionary values: ")print(dict_values)
Output: List of dictionary values: dict_values(['Mahika', 17, 'Female'])

12. str():

This method creates a printable string representation of a dictionary. The basic form of using this method is as follows:


Example 12:

# Python program to print a string representation of dictionary.my_dict = {"Name": "Mahika", "Age": 17, "Gender": "Female"}# Call str() function to get string representation of a dictionary.print("String representation of dictionary: ")print(str(my_dict))
Output: String representation of dictionary: {'Name': 'Mahika', 'Age': 17, 'Gender': 'Female'}

Built-in Functions Used on Dictionaries

There are several built-in functions provided by Python language used on dictionaries for which we can pass an argument as a dictionary. They are as:

  • all()
  • any()
  • len()
  • cmp()
  • sorted()
  • type()

In this tutorial, we have discussed all the dictionary methods and built-in functions in Python with the help of examples. Hope that you will have understood the basic points of each dictionary method and practiced all example programs based on methods.
Thanks for reading!!!


What are the functions and methods for dictionary? ›

Python Dictionary Methods
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
7 more rows

Can you have functions in a dictionary Python? ›

The technique is when you have a python dictionary and a function that you intend to use on it. You insert an extra element into the dict, whose value is the name of the function. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name.

How to use dictionary methods in Python? ›

How to Create a Dictionary in Python. To create a dictionary, you open up a curly brace and put the data in a key-value pair separated by commas. Note that the values can be of any data type and can be duplicated, but the key must not be duplicated. If the keys are duplicated, you will get an invalid syntax error.

How do you define a function in a dictionary in Python? ›

Python defines a function by executing a def statement. Python defines your dict by executing your d = { etc etc etc} .

What are the five functions of dictionary? ›

In addition to its basic function of defining words, a dictionary may provide information about their pronunciation, grammatical forms and functions, etymologies, syntactic peculiarities, variant spellings, and antonyms.

What are methods or functions in Python? ›

The method operates the data in the class, while a function is used to return or pass the data. A function can be directly called by its name, while a method can't be called by its name. The method lies under Object-Oriented Programming, while a function is an independent functionality.

Which functions can be used as the keys for dictionaries in Python? ›

keys() method in Python is used to retrieve all of the keys from the dictionary. The keys must be of an immutable type (string, number, or tuple with immutable elements) and must be unique. Each key is separated from its value by a colon(:). An item has a key and a value is stated as a pair (key : pair).

How do you apply a function to all values in a dictionary in Python? ›

You can use the toolz. valmap() function to apply a function to the dictionary's values. Similarly, to apply function to keys of a dictionary, use toolz. keymap() function and to apply function to items of a dictionary, use toolz.

Can a Python function return a dictionary? ›

Any object, such as dictionary, can be the return value of a Python function. Create the dictionary object in the function body, assign it to any variable, and return the dictionary to the function's caller. Data values are stored as key:value pairs in dictionaries.

What are the two functions of the dictionary? ›

Its most general functions are the following: The dictionary provides information on parts and aspects of the lexicon of one language. This is a monolingual dictionary. The dictionary provides help in translating between languages.

What are __ dict __ methods in Python? ›

What is __dict__ method? According to python documentation object. __dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__.

What are the basic operations of a dictionary? ›

Main operations on dictionaries

insert or update a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one) remove a key-value pair. test for existence of a key.

What function finds value in dictionary Python? ›

Python provides a . get() method to access a dictionary value if it exists. This method takes the key as the first argument and an optional default value as the second argument, and it returns the value for the specified key if key is in the dictionary.

What are the main functions of a data dictionary? ›

A data dictionary is used to catalog and communicate the structure and content of data, and provides meaningful descriptions for individually named data objects.

What are the 5 different types of dictionary? ›

Dictionary Types
  • Bilingual Dictionary.
  • Monolingual Dictionary.
  • Etymological Dictionary.
  • Crossword Dictionary.
  • Rhyming Dictionary.
  • Mini-Dictionary.
  • Pocket Dictionary.
  • Thesaurus.

What are the four features of dictionary in Python? ›

Dictionaries and lists share the following characteristics:
  • Both are mutable.
  • Both are dynamic. They can grow and shrink as needed.
  • Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

What are the most useful functions and methods in Python? ›

Q1. What are the most useful functions in Python? Some of the most useful functions in Python are print(), abs(), round(), min(), max(), sorted(), sum(), and len().

How many different functions are there in Python? ›

There are 68 built-in python functions. These functions perform a specific task and can be used in any program, depending on the requirement of the user. 1 What are Python Functions?

What is main function and method in Python? ›

What is Main Function in Python. In most programming languages, there is a special function which is executed automatically every time the program is run. This is nothing but the main function, or main() as it is usually denoted. It essentially serves as a starting point for the execution of a program.

What are built in dictionary functions explain with examples? ›

Built-in Dictionary Functions & Methods in Python
Sr.NoFunction with Description
1cmp(dict1, dict2) Compares elements of both dict.
2len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3str(dict) Produces a printable string representation of a dictionary
1 more row
Jan 28, 2020

What does the keys () dictionary method do? ›

Python dictionary keys() function is used to return a new view object that contains a list of all the keys in the dictionary. The Python dictionary keys() method returns an object that contains all the keys in a dictionary.

What is the difference between keys and dictionary in Python? ›

Keys will be a single element. Values can be a list or list within a list, numbers, etc. More than one entry per key is not allowed ( no duplicate key is allowed) The values in the dictionary can be of any type, while the keys must be immutable like numbers, tuples, or strings.

How to check all values in a dictionary Python? ›

We can use the values() method in Python to retrieve all values from a dictionary. Python's built-in values() method returns a view object that represents a list of dictionaries containing every value.

How to convert all values to string in dictionary Python? ›

You can easily convert a Python dictionary to a string using the str() function. The str() function takes an object (since everything in Python is an object) as an input parameter and returns a string variant of that object. Note that it does not do any changes in the dictionary itself but returns a string variant.

Can a Python dictionary have multiple values? ›

Thus we have inferred in this article that a single key can have multiple values in a dictionary in Python.

Does Python dictionary remove duplicates? ›

Dictionaries in Python cannot include duplicate keys. If we convert our list to a dictionary, it will remove any duplicate values.

Can a Python dictionary have two of the same keys? ›

Dictionary in python is ordered, changeable, and does not allow duplicates. That means the dictionary cannot have two items with the same key; hence, dictionary keys are immutable. Check how to create a python dictionary to learn more.

Can I return 2 values from a function in Python? ›

You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list containing the number of miles to run each week. Data structures in Python are used to store collections of data, which can be returned from functions.

What are the six uses of dictionary? ›

Dictionaries can help you in your reading and writing, and to improve your vocabulary. A dictionary can be used to look up the meaning of a word. You can also use a dictionary to check the spelling of a word. Dictionaries may also give other information about words, such as word type and word origin.

What are the 3 features of dictionary? ›

Features of a good dictionary
  • Meaning. The most important information about a word that a dictionary contains is the meaning. ...
  • Usage. A good dictionary will also provide examples of usage. ...
  • Grammatical information. A good dictionary will give grammatical information about each word. ...
  • Spelling. ...
  • Pronunciation. ...
  • Other information.
Dec 31, 2022

What are the three types of dictionary? ›

There are many different types of dictionaries. The three main types are monolingual, bilingual, and bilingualized. There are also thesauruses, which are not dictionaries but are closely related.

What is the difference between __ dict __ and dir? ›

Class dir() and dict only show defined functions (methods). Instance dir() shows data+methods while its dict only shows data attributes, not methods.

What is Vars () in Python? ›

Python vars() Function

The vars() function returns the __dict__ attribute of an object. The __dict__ attribute is a dictionary containing the object's changeable attributes. Note: calling the vars() function without parameters will return a dictionary containing the local symbol table.

What is the magic method in Python dict? ›

The magic methods are used to construct and initialise new objects, they help us retrieve an object as a dictionary, they are used to delete an object amongst other operations. They are used when the + operator is invoked, or even when we want to represent an object as a string.

What are the four main content of a dictionary? ›

What are the parts of a dictionary? Words, definitions (the meaning of a word), the pronunciation of each word using the special spelling and pronunciation key, and examples of how to use the word in a sentence. The dictionary may include synonyms of the word. Thanks!

What is dictionary in Python with example? ›

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

What are the structures of a dictionary? ›

Structures of A Dictionary

A dictionary is composed of four parts: Megastructure, Macrostructure, Mesostructure and Microstructure.

What does the dictionary method values () return? ›

The values() method returns a view object. The view object contains the values of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example below.

How do you check if a string is in a dictionary Python? ›

The simplest way to check is by using the 'in' operator. The 'in' operator can be used as a condition in an if statement to find out if the key is in the dictionary or not. It is a boolean operator that returns True if the key is present in the dictionary and False otherwise.

What does dictionary values () return? ›

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function.

What are the functions of a dictionary ADT? ›

The dictionary ADT provides operations for storing records, finding records, and removing records from the collection. This ADT gives us a standard basis for comparing various data structures. Loosly speaking, we can say that any data structure that supports insert, search, and deletion is a “dictionary”.

What are the functions of data dictionary? ›

Data dictionaries are used to provide detailed information about the contents of a dataset or database, such as the names of measured variables, their data types or formats, and text descriptions. A data dictionary provides a concise guide to understanding and using the data.

What is a function word dictionary? ›

a word, as a preposition, article, auxiliary, or pronoun, that chiefly expresses grammatical relationships, has little semantic content of its own, and belongs to a small, closed class of words whose membership is relatively fixed (distinguished from content word).

What are the two main types of data dictionary? ›

There are two types of data dictionaries: active and passive. An active data dictionary is tied to a specific database which makes data transference a challenge, but it updates automatically with the data management system.

Which of the following functions of dictionary gets all the keys from the dictionary? ›

Explanation. Using dictionary. keys() function, we can get all the keys from the dictionary object.

What are dictionary data types? ›

There are two types of data dictionaries: active and passive.

What is the data structure for a dictionary? ›

A dictionary is a general-purpose data structure for storing a group of objects. A dictionary has a set of keys and each key has a single associated value. When presented with a key the dictionary will • A dictionary has a set of keys and each key has a single associated value.

What is difference between data dictionary and metadata? ›

A Data Dictionary is an integral part of a database. It holds the information about the database and the data that it stores called as metadata. A meta data is the data about the data. It is the self-describing nature of databases.

What is the difference between data mapping and data dictionary? ›

The Difference Between a Data Dictionary and a Data Mapping Specification. A data dictionary defines the data elements, meanings, and allowable values, often for a single data source. A data mapping specification defines how information from one system or data source maps to a separate system or data source.

What is an example of a good data dictionary? ›

A good example of a data dictionary is the one used by ORNL (Oak Ridge National Laboratory). ORNL maintains this dictionary as a PDF and it resembles a detailed index at the end of a book. The document provides basic information (entry type and description) on each entry, called a variable.

What is the difference between data dictionary and schema? ›

schema vs. data catalog. There's some overlap here with a database's schema, but generally speaking a schema defines the structure of the database and how tables and their fields fit together, while a data dictionary provides contextual information about that data.

What are the 7 function words? ›

Function words include determiners, conjunctions, prepositions, pronouns, auxiliary verbs, modals, qualifiers, and question words.

What are the four types of word functions? ›

Function Word Types
  • Auxiliary verbs = do, be, have (help with conjugation of tense)
  • Prepositions = show relationships in time and space.
  • Articles = used to indicate specific or non-specific nouns.
  • Conjunctions = words that connect.
  • Pronouns = refer to other nouns.
Oct 2, 2018

How do you determine a function? ›

Use the vertical line test to determine whether or not a graph represents a function. If a vertical line is moved across the graph and, at any time, touches the graph at only one point, then the graph is a function. If the vertical line touches the graph at more than one point, then the graph is not a function.

Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated: 04/29/2023

Views: 5643

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.