How to search Python dictionary for matching key?

PythonProgramming

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
raja
Published on 18-Apr-2018 13:14:12
Advertisements