Open In App

Python – Access Dictionary items

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.

Example:

Python
a = {"Geeks": 3, "for": 2, "geeks": 1}

#Access the value assosiated with "geeks"
x = a["geeks"]
print(x)

Output
1

Let’s explore various ways to access keys, values or items in the Dictionary.

Using get() Method

We can access dictionary items by using get() method. This method returns None if the key is not found instead of raising an error. Additionally, we can specify a default value that will be returned if the key is not found:

Python
a = {"Geeks": 3, "for": 2, "geeks": 1}

#Accessing value associated with "for" 
value = a.get("for")
print(value)

Output
2

Accessing Keys, Values, and Items

By using methods like keys(), values(), and items() methods we can easily access required items from the dictionary.

Get all Keys Using key() Method

In Python dictionaries, 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.

Python
a = {"geeks": 3, "for": 2, "Geeks": 1}

#Looping through the keys of the dictionary
keys = a.keys()
print(keys)

Output
dict_keys(['geeks', 'for', 'Geeks'])

Get all values 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.

Python
a = {"geeks": 3, "for": 2, "Geeks": 1}

# Accessing values using values() method
values = a.values()
print(values )

Output
dict_values([3, 2, 1])

Using ‘in’ Operator

The in is 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. 

Python
a = {'geeks': 3, 'for': 2, 'Geeks': 1}  

# Looping through each key in the dictionary 'a'
for key in a:  
    print(key, a[key])  

Output
geeks 3
for 2
Geeks 1

Get key-value Using dict.items()

The items() method allows you to iterate over both keys and values simultaneously. It returns a view of key-value pairs in the dictionary as tuples.

Python
a = {'geeks': 3, 'for': 2, 'Geeks': 1}   

# Iterating through key-value pairs
for key, value in a.items():  
    print(f"{key}: {value}")  

Output
geeks: 3
for: 2
Geeks: 1

Also Read:



Next Article

Similar Reads