Open In App

Access Dictionary Values | Python Tutorial

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A dictionary is quite a useful data structure in Python programming that is usually used to hash a particular key with value so that it can be retrieved efficiently.

To access an item in the dictionary, refer to its key name inside square brackets.

Example

Python3




dict = {
  "country" : "India",
  "continent" : "Asia",
  "Other_name" : "Bharat"
}
x = dict["continent"]
print(x)


Output

Asia

We used a very basic and default method to access a dictionary item using it’s key. We will discuss more advanced methods to access value in dictionary.

How to Access Values in Dictionary

There are various ways to access items in the Dictionary or call dictionary value, we are explaining some generally used and easy methods we use for accessing Items (key-value) in the dictionary:

  • Using key() Method
  • Using values() Method
  • Using an operator
  • Using List Comprehension
  • Using dict.items()
  • Using enumerate() Method
  • Using for loop and items() method

Printing Dictionary Using print() and str() Functions

In this example, we call dictionary value. Below Python code initializes a dictionary named test_dict with key-value pairs. It then prints the original dictionary using the print function and the str() function for converting the dictionary to a string for display purposes.

Python3




# Python3 code to demonstrate
# to get key and value
# using in operator
 
# initializing dictionary
test_dict = {"Geeks": 1, "for": 2, "geeks": 3}
 
# Printing dictionary
print("Original dictionary is : " + str(test_dict))


Output :

Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}

1. Access Items in Dictionary using key() Method

In Python dictionaries, the keys() method returns a view of the keys. By iterating through this view using a for loop, you can access keys in the dictionary efficiently. This approach simplifies key-specific operations without the need for additional methods.

Example: In this example below code iterates through the keys of the test_dict dictionary and prints each key along with its corresponding value.

Python3




# Accessing key-value pairs using keys() method
for key in test_dict.keys():
    print("Key:", key, "Value:", test_dict[key])


Output :

Key: Geeks Value: 1Key: for Value: 2Key: geeks Value: 3

Time Complexity :O(n)
Space Complexity : O(n)

2. Access the Value in Dictionary using values() Method

In Python, we can access the values in a dictionary using the values() method. This method returns a view of all values in the dictionary, allowing you to iterate through them using a for loop or convert them to a list.

Example: In this example, the code iterates through the values of the test_dict dictionary and prints each value.

Python3




# Accessing values using values() method
for value in test_dict.values():
    print("Value:", value )


Output :

Value: 1Value: 2Value: 3

Time complexity :O(n)
Space Compexity : O(n)

3. Access Dictionary Items using ‘in’ Operator

The most used method that can get all the keys along with its value, thein” operator is widely used for this very purpose and highly recommended as it offers a concise method to achieve this task. 

Example: In the example below Python code prints the key-value pairs of a dictionary using the `in` operator. It initializes a dictionary, iterates through its keys, and prints each key along with its corresponding value.

Python3




# using in operator to
# get key and value
print("Dict key-value are : ")
for i in test_dict:
    print(i, test_dict[i])


Output:

Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are :
geeks 3
for 2
Geeks 1

Time Complexity: O(n)
Auxiliary Space: O(1)

4. Access a Dictionary Items using List Comprehension

This method also uses a method similar to the above method, it just binds the logic into one list and returns the key-value pairs of a dictionary as tuples of key and value in the list. 

Example: In this example the below code utilizes dictionary comprehension to convert a dictionary into a list of key-value pairs using list comprehension, demonstrating the original dictionary and the resulting list of tuples.

Python3




# using list comprehension to
# get key and value
print("Dict key-value are : ")
print([(k, test_dict[k]) for k in test_dict])


Output:

Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}
Dict key-value are :
[('Geeks', 1), ('for', 2), ('geeks', 3)]

Time Complexity: O(n)
Auxiliary Space: O(1)

5. Access Items in a Dictionary Using dict.items()

Python dictionary items() method iterates over all the keys and helps us to access the key-value pair one after the other in the loop and is also a good method to access dictionary keys with value. 

Example: In this example, the below code demonstrates how to retrieve both keys and values from a dictionary in Python. It initializes a dictionary, prints the original dictionary, and then uses a loop with `dict.items()` to print each key-value pair in the dictionary.

Python3




# using dict.items() to
# get key and value
print("Dict key-value are : ")
for key, value in test_dict.items():
    print(key, value)


Output:

Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are :
geeks 3
for 2
Geeks 1

Time Complexity: O(n)
Auxiliary Space: O(1)

6. Access Items in Dictionary using enumerate()

enumerate() in Python helps to iterate over all kinds of containers, be it a dictionary or a list. The power of this function can also be utilized to perform this task. It also additionally helps to access the named index of the position of the pair in the dictionary. 

Example: In this example, the below code uses Python’s `enumerate()` function to iterate over the key-value pairs of a dictionary (`test_dict`). It prints the original dictionary and then uses `enumerate()` with `items()` to display the key-value pairs along with their indices.

Python3




# using enumerate() to
# get key and value
print("Dict key-value are : ")
for i in enumerate(test_dict.items()):
    print(i)


Output:

Original dictionary is : {'geeks': 3, 'Geeks': 1, 'for': 2}
Dict key-value are :
(0, ('geeks', 3))
(1, ('Geeks', 1))
(2, ('for', 2))

Time Complexity: O(n)
Auxiliary Space: O(1)

6. Access Values of the Dictionary using For loop and Items() Method

In Python, you can access items in a dictionary using a for loop and the items() method. The loop iterates over key-value pairs, allowing you to process both keys and corresponding values. This concise approach simplifies dictionary traversal, enhancing code readability and efficiency.

Example: In this example, the below code initializes a dictionary, prints it, and then extracts key-value pairs using a for loop and `items()`. The pairs are stored in a list and printed, showcasing the iteration over dictionary items for access and manipulation.

Python3




# Initializing an empty list
key_value_pairs = []
 
# Using a for loop to iterate over the items in the dictionary
# and append each key-value pair to the list
for key, value in test_dict.items():
    key_value_pairs.append((key, value))
 
# Printing the key-value pairs
print("Dict key-value are : ")
for pair in key_value_pairs:
    print(pair)


Output:

Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}
Dict key-value are :
('Geeks', 1)
('for', 2)
('geeks', 3)

Time complexity :O(n)
Space Complexity : O(n)

We have covered easy methods on “How to access values in dictionary”, you can easily access the dictionary values using these methods. Accessing values in a dictionary is very important for data manipulation, updation, deletion, etc. 

Also Read:



Previous Article
Next Article

Similar Reads

How to Access Dictionary Values in Python Using For Loop
A dictionary is a built-in data type in Python designed to store key-value pairs of data. The most common method to access values in Python is through the use of a for loop. This article explores various approaches to accessing values in a dictionary using a for loop. Access Dictionary Values in Python Using For LoopBelow, we are explaining the exa
2 min read
Access Dictionary Values Given by User in Python
Dictionaries are a fundamental data structure in Python, providing a flexible way to store and retrieve data using key-value pairs. Accessing dictionary values is a common operation in programming, and Python offers various methods to accomplish this task efficiently. In this article, we will explore some generally used methods to access dictionary
4 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 program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read