Open In App

Dictionaries in Python

Last Updated : 19 Jun, 2024
Like Article
dict = {
  1: 'Python', 
  2: 'dictionary', 
  3: 'example'

A Python dictionary is a data structure that stores the value in key:value pairs.


As you can see from the example, data is stored in key:value pairs in dictionaries, which makes it easier to find values.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Python Dictionary Syntax

dict_var = {key1 : value1, key2 : value2, …..}

What is a Dictionary in Python?

Dictionaries in Python is a data structure, used to store values in key:value format. This makes it different from lists, tuples, and arrays as in a dictionary each key has an associated value.

Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate keys.

How to Create a Dictionary

In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by a ‘comma’.

The dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value.

Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable

Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly. 

The code demonstrates creating dictionaries with different types of keys. The first dictionary uses integer keys, and the second dictionary uses a mix of string and integer keys with corresponding values. This showcases the flexibility of Python dictionaries in handling various data types as keys.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")


Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys: 
{'Name': 'Geeks', 1: [1, 2, 3, 4]}

Dictionary Example

A dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing curly braces{}. 

Different Ways to Create a Python Dictionary

The code demonstrates different ways to create dictionaries in Python. It first creates an empty dictionary, and then shows how to create dictionaries using the dict() constructor with key-value pairs specified within curly braces and as a list of tuples.

Dict = {}
print("Empty Dictionary: ")

Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")

Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")


Empty Dictionary: 
Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair: 
{1: 'Geeks', 2: 'For'}

Complexities for Creating a Dictionary:

  • Time complexity: O(len(dict))
  • Space complexity: O(n)

Nested Dictionaries

Example: The code defines a nested dictionary named ‘Dict’ with multiple levels of key-value pairs. It includes a top-level dictionary with keys 1, 2, and 3. The value associated with key 3 is another dictionary with keys ‘A,’ ‘B,’ and ‘C.’ This showcases how Python dictionaries can be nested to create hierarchical data structures.

Dict = {1: 'Geeks', 2: 'For',
        3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}



{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

More on Python Nested Dictionary

Adding Elements to a Dictionary

The addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.

Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary. 

Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

Example: Add Items to a Python Dictionary with Different DataTypes

The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates adding elements with various data types, updating a key’s value, and even nesting dictionaries within the main dictionary. The code shows how to manipulate dictionaries in Python.

Dict = {}
print("Empty Dictionary: ")
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")

Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")

Dict[2] = 'Welcome'
print("\nUpdated key value: ")
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")


Empty Dictionary: 
Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value: 
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key: 
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: 
{'Nested': {'1': 'Life', '2': 'Geeks'}}}

Complexities for Adding Elements in a Dictionary:

  • Time complexity: O(1)/O(n)
  • Space complexity: O(1)

Accessing Elements of a Dictionary

To access the items of a dictionary refer to its key name. Key can be used inside square brackets. 

Access a Value in Python Dictionary

The code demonstrates how to access elements in a dictionary using keys. It accesses and prints the values associated with the keys ‘name’ and 1, showcasing that keys can be of different data types (string and integer).

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Accessing a element using key:")
print("Accessing a element using key:")


Accessing a element using key:
Accessing a element using key:

There is also a method called get() that will also help in accessing the element from a dictionary. This method accepts key as argument and returns the value.

Complexities for Accessing elements in a Dictionary:

  • Time complexity: O(1)
  • Space complexity: O(1)

Example: Access a Value in Dictionary using get() in Python

The code demonstrates accessing a dictionary element using the get() method. It retrieves and prints the value associated with the key 3 in the dictionary ‘Dict’. This method provides a safe way to access dictionary values, avoiding KeyError if the key doesn’t exist.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Accessing a element using get:")


Accessing a element using get:

Accessing an Element of a Nested Dictionary

To access the value of any key in the nested dictionary, use indexing [] syntax.

Example: The code works with nested dictionaries. It first accesses and prints the entire nested dictionary associated with the key ‘Dict1’. Then, it accesses and prints a specific value by navigating through the nested dictionaries. Finally, it retrieves and prints the value associated with the key ‘Name’ within the nested dictionary under ‘Dict2’.

Dict = {'Dict1': {1: 'Geeks'},
        'Dict2': {'Name': 'For'}}



{1: 'Geeks'}

Deleting Elements using ‘del’ Keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Example: The code defines a dictionary, prints its original content, and then uses the ‘del’ statement to delete the element associated with key 1. After deletion, it prints the updated dictionary, showing that the specified element has been removed.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Dictionary =")
print("Data after deletion Dictionary=")


Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}

Dictionary Methods

Here is a list of in-built dictionary functions with their description. You can use these functions to operate on a dictionary.

dict.clear()Remove all the elements from the dictionary
dict.copy()Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
dict.items() Returns a list containing a tuple for each key value pair
dict.keys() Returns a list containing dictionary’s keys
dict.update(dict2)Updates dictionary with specified key-value pairs
dict.values() Returns a list of all the values of dictionary
pop() Remove the element with specified key
popItem()Removes the last inserted key-value pair
 dict.setdefault(key,default= “None”)set the key to the default value if the key is not specified in the dictionary
dict.has_key(key)returns true if the dictionary contains the specified key.

For Detailed Explanations: Python Dictionary Methods

Multiple Dictionary Operations in Python

The code begins with a dictionary ‘dict1’ and creates a copy ‘dict2’. It then demonstrates several dictionary operations: clearing ‘dict1’, accessing values, retrieving key-value pairs and keys, removing specific key-value pairs, updating a value, and retrieving values. These operations showcase how to work with dictionaries in Python.

dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
dict2 = dict1.copy()
dict2.update({3: "Scala"})


{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])

We have covered all about dictionaries in Python, discussed its definition, and uses, and saw different dictionary methods with examples. The dictionary is an important data structure for storing data in Python. It is very different from tuples and lists.

Read More Data Structures in Python

Also Read:

Dictionaries in Python – FAQs

How to use dictionaries in Python?

Dictionaries in Python are used to store key-value pairs. They are unordered, mutable, and can contain any Python objects as values.

# Creating a dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
# Accessing values by keys
print(my_dict['key1'])  # Output: value1
# Modifying values
my_dict['key2'] = 'new_value'
# Adding new key-value pairs
my_dict['key3'] = 'value3'
# Removing a key-value pair
del my_dict['key1']

How to print dictionaries in Python?

You can use print() to display the contents of a dictionary. You can print the entire dictionary or specific elements by accessing keys or values.

my_dict = {'name': 'Alice', 'age': 30}
# Printing the entire dictionary
# Printing specific elements
print(my_dict['name'])  # Output: Alice

How to declare a dictionary in Python?

You can declare a dictionary by enclosing key-value pairs within curly braces {}.

# Empty dictionary
empty_dict = {}
# Dictionary with initial values
my_dict = {'key1': 'value1', 'key2': 'value2'}

What are dictionary keys and values in Python?

In a dictionary, keys are unique identifiers that are used to access values. Values are the data associated with those keys.

my_dict = {'name': 'Alice', 'age': 30}
# Accessing keys and values
print(my_dict.keys())    # Output: dict_keys(['name', 'age'])
print(my_dict.values())  # Output: dict_values(['Alice', 30])

What is the use of all(), any(), cmp(), and sorted() in dictionary?

  • all() checks if all values in the dictionary evaluate to True.
  • any() checks if any value in the dictionary evaluates to True.
  • cmp() (no longer available in Python 3) used to compare two dictionaries.
  • sorted() returns a new sorted list of keys in the dictionary.
my_dict = {'A': 10, 'B': 20, 'C': 0}
print(all(my_dict.values()))   # False (0 evaluates to False)
print(any(my_dict.values()))   # True (at least one value is True)
print(sorted(my_dict))         # ['A', 'B', 'C'] (sorted keys)

    Similar Reads

    Python - Convert Dictionaries List to Order Key Nested dictionaries
    Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
    6 min read
    Python Program to extract Dictionaries with given Key from a list of dictionaries
    Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
    6 min read
    Convert Dictionary of Dictionaries to Python List of Dictionaries
    Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
    3 min read
    Filter List of Python Dictionaries by Key in Python
    Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
    3 min read
    Python | Sort Python Dictionaries by Key or Value
    There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
    7 min read
    Handling missing keys in Python dictionaries
    In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
    4 min read
    Ways to sort list of dictionaries by values in Python - Using lambda function
    In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
    2 min read
    Ways to sort list of dictionaries by values in Python – Using itemgetter
    In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article. In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently utilized in a variety of applications, from those i
    3 min read
    Python | Common items among dictionaries
    Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehension This particular task
    6 min read
    Python | Set Difference in list of dictionaries
    The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The naive method to iterate both the list and extract th
    3 min read
    Practice Tags :