Last Updated : 11 Jul, 2025
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)
Let's explore various ways to access keys, values or items in the Dictionary.
Using get() MethodWe 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)
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() MethodIn 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)
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 )
dict_values([3, 2, 1])Using 'in' Operator
The in is most used method that can get all the keys along with its value, the "in" 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])
geeks 3 for 2 Geeks 1Get 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}")
geeks: 3 for: 2 Geeks: 1
Also Read:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4