How to search Python dictionary for matching key?


If you have the exact key you want to find, then you can simply use the [] operator or get the function to get the value associated with this key. For example,

Example

a = {
   'foo': 45,
   'bar': 22
}
print(a['foo'])
print(a.get('foo'))

Output

This will give the output:

45
45

Example

If you have a substring that you want to search in the dict, you can use substring search on the keys list and if you find it, use the value. For example,

a = {
   'foo': 45,
   'bar': 22
}
for key in a.keys():
   if key.find('oo') > -1:
      print(a[key])

Output

This will give the output

45

Updated on: 17-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements