![]() |
VOOZH | about |
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:
1
Let's explore various ways to access keys, values or items in the Dictionary.
Table of Content
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:
2
By using methods like keys(), values(), and items() methods we can easily access required items from the dictionary.
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.
dict_keys(['geeks', 'for', 'Geeks'])
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.
dict_values([3, 2, 1])
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.
geeks 3 for 2 Geeks 1
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.