Hello Pythonistas, welcome back.
Today we will see different ways of extracting values and keys from a python dictionary.
Contents
How to extract value from a Python dictionary using key?
Let’s say your friend comes to your shop to buy an apple🍎. Then you search in your dict where’s my apple this way:-
where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what['apple'])
Output:-
top row of shelf
You can make results look even more clear using an f-string:
print(f"Where's my apple? It is in the:- {where_is_what['apple']}")
Output:-
Where's my apple? It is in the:- top row of shelf
Similarly, you can easily access any other item’s location.
It’s been a month and you are making great progress in the store and decided to expand your product line and make a few changes. Let’s do them.
Time ⌚ to take a look at some amazing functions/methods on dictionaries.
How to extract all values from a dictionary in Python?
In case you wish to extract all the values from the dictionary you can use the values() method:
where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what.values())
Output:-
dict_values(['top row of shelf', 'bottom row of the shelf', 'middle row of the shelf'])
How do you print all the keys from a dictionary in Python?
If you want to know what items are there in your shop (you want to access all the keys) then, you can use the keys() method:
where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what.keys())
Output:-
dict_keys(['apple', 'banana', 'spinach'])
How to get key by value in a Python dictionary?
Although Python offers no such method you can use any of these 3 tricks:
- for Loop
Step1: Store the value(whose key you want)
value = "top row of shelf"
Step2: Run a loop
for key, val in where_is_what:
if(val == value):
req_key = key
#the key we wanted
print(key)
Output:
apple
- Lists
- Get the keys (using .keys())
- Get the values (using .values())
- Get the index of the value you want (index(val) of list)
- Get the same index from the key list. (key_lst[index])
- List Comprehension
You just repeat the first method but write it in a crisp manner:
value = "top row of shelf"
req_key = [key for key, val in items if val == value]
print(f"The key of {value} in the dictionary is: ", req_key)
Output:
apple