There are several ways to access Python Dictionary
1. By referring to key name:
The items of a dictionary can be accessed by referring to its key name, inside square brackets.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1[1])
Output: apple
There is also a method called get()
that will give you the same result.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.get(1))
Output: apple
Note: If we use the square brackets []
, KeyError
is raised in case a key is not found in the dictionary. On the other hand, the get()
method returns None
if the key is not found.
2. By using key() method:
It will return a list of all the keys in the dictionary.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.keys())
Output: dict_keys([1, 2, 3])
3. By using value() method:
It will return a list of all the values in the dictionary.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.values())
Output: dict_values(['apple', 'papaya', 'pineapple'])
4. By using dict.items():
This method will return each item in a dictionary, as tuples in a list. It is also a good method to access dictionary keys with value.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.items())
Output: dict_items([(1, 'apple'), (2, 'papaya'), (3, 'pineapple')])
5. By using in operator:
This method is used to get possibly all the keys along with its value.
Example:
dict_1={1:'apple',2:'papaya',3:'pineapple'}
for i in dict_1 :
print(i, dict_1[i])
Output:
1 apple 2 papaya 3 pineapple
6. By using enumerate():
It helps to iterate over all kinds of containers, be it dictionary or a list. It also additionally helps to access the named index of position of the pair in dictionary.
Example:
dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
for i in enumerate(dict_1.items()):
print (i)
Output:
(0, (1, 'apple')) (1, (2, 'papaya')) (2, (3, 'pineapple'))
- Log in to post comments