python: find all keys with a value

how to get specific key value from dictionary in python
python dictionary get key from value
python find key in dictionary
python list of dictionaries get value
find key value pair in dictionary python
get dictionary key values
find index of value in dictionary python
python dictionary same key multiple values

I have a dictionary like below:

mydict = {'a' : 'apple',
     'b' : 'bobb',
    'c' : {
         'd' : 'dog'
       },
      'e' : 'dog'
     }

Suppose I want to find all the keys with value 'dog'In case of nesting, the keys should be separated by a dot.

So the output should be a list ['e', 'c.d']

Now if I write below code in python 3, it only outputs 'e'.

print(list(mydict.keys())[list(mydict.values()).index('dog')])

How can I get the nested keys?

You can use a recursion function like following:

def find_key(mydict, pre=tuple()):
    for key, value in mydict.items():
        if isinstance(value, dict):
            yield from find_key(value, pre=pre+(key,))
        elif value == 'dog':
            if pre:
                yield '.'.join(pre + (key,))
            else:
                yield key

test:

In [23]: list(find_key(mydict))
Out[23]: ['e', 'c.d']
In [26]: mydict = {'a' : 'apple',
     'b' : 'bobb',
    'c' : {
         'd' : 'dog'
       },
      'e' : 'dog',
     'k':{'f':{'c':{'x':'dog'}}}}

In [27]: 

In [27]: list(find_key(mydict))
Out[27]: ['k.f.c.x', 'e', 'c.d']

Find all Key-Elements by the same Value in Dicts, I have question about Dictionaries in Python. here it is: I have a dict like dict = { '​abc':'a', 'cdf':'b', 'gh':'  Python. ''' Get a list of keys from dictionary which has the given value ''' def getKeysByValue (dictOfElements, valueToFind): listOfKeys = list () listOfItems = dictOfElements.items () for item in listOfItems: if item [1] == valueToFind: listOfKeys.append (item [0]) return listOfKeys. 1.

You can use recursion (although @Kasramvd beat me to it, here is a non-generator version for good measure):

>>> def find_key(value, d, level=None, acc=None):
...     acc = acc if acc is not None else []
...     level = level if level is not None else []
...     for k,v in d.items():
...         if isinstance(v, dict):
...             find_key(value, v, level=[*level, k], acc=acc)
...         elif v == value:
...             acc.append('.'.join([*level,k]))
...     return acc
...
>>>
>>> find_key('dog', mydict)
['c.d', 'e']

And with Kasramvd's messier test-case:

>>> mydict = {'a' : 'apple',
...      'b' : 'bobb',
...     'c' : {
...          'd' : 'dog'
...        },
...       'e' : 'dog',
...      'k':{'f':{'c':{'x':'dog'}}}}
>>> find_key('dog', mydict)
['c.d', 'e', 'k.f.c.x']

Python : How to find keys by value in dictionary ? – thispointer.com, items() returns an iterable sequence of all key value pairs in dictionary. So, we will iterate over this sequence and for each entry we will check if  So, we passed a key function too i.e. Python. key=lambda x : x [1] 1. key=lambda x : x[1] This key function accepts a tuple as an argument and returns the 2nd value in tuple i.e. item at index 1. So, basically when a tuple of key, value is passed to this function, it returns the value field from that tuple.

You can also use recursion with a list comprehension:

mydict1 = {'a' : 'apple',
    'b' : 'bobb',
    'c' : {
       'd' : 'dog'
      },
     'e' : 'dog'
     }

mydict = {'a' : 'apple',
 'b' : 'bobb',
'c' : {
     'd' : 'dog'
   },
  'e' : 'dog',
 'k':{'f':{'c':{'x':'dog'}}}}

s = [mydict1, mydict]
def get_val(d, target='dog'):
  return reduce(lambda x, y:([x] if isinstance(x, str) else x)+([y] if isinstance(y, str) else y), list(filter(None, [a if b == target else "{}.{}".format(a, get_val(b)) if isinstance(b, dict) else None for a, b in d.items()])))


new_s = list(map(get_val, s))

Output:

[['c.d', 'e'], ['c.d', 'e', 'k.f.c.x']]

Python : How to get all keys with maximum value in a Dictionary , Now in the above example to find the key with max value in dictionary. We passed the Iterable returns by dict.items(), that is basically an Iterable  Search keys in a dictionary by the list of values. In this exercise, we’ll find out keys whose value are matching once given in below list: [5, 6] To achieve this, we’ll traverse the iterable sequence, the output of the dict.items() function. We’ll then test if the value matches with some entry from the above input list.

Here you go :

mydict = {'a' : 'apple',
     'b' : 'bobb',
    'c' : {
         'd' : 'dog'
       },
      'e' : 'dog',
     'k':{'f':{'c':{'x':'dog'}}},

      'p':{'r':{'h':{'m':{'n':{'o':{'a':{'b':{'t':{'z':{'a':{'b':{'c':{'d':{'e':{'f':{'g':'dog'}}}}}}}}}}}}}}}}







          }

your_word='dog'

result = []

for key,value in mydict.items():
    if value==your_word:
        result.append(key)
    elif isinstance(value,dict):

        def recursive_approach(my_dict, nested_dict=key):

            for i, j in my_dict.items():
                if isinstance(j, dict):

                    nested_dict = "{}.{}".format(nested_dict, i)


                    return recursive_approach(j, nested_dict)
                else:
                    if nested_dict == '':

                        if j == your_word:
                            result.append(i)
                    else:
                        if j == your_word:
                            result.append("{}.{}".format(nested_dict, i))


        recursive_approach(value)





print(result)

output:

['p.r.h.m.n.o.a.b.t.z.a.b.c.d.e.f.g', 'k.f.c.x', 'e', 'c.d']

Python, Given a dictionary, the task is to find keys with duplicate values. Python code to demonstrate. # finding duplicate values from a dictionary Please write to us at contribute@geeksforgeeks.org to report any issue with the above content. Given a dictionary, the task is to find keys with duplicate values. Let’s discuss a few methods for the same. Suppose you need to find keys having duplicate values. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your

Python, The approach used here is to find two separate lists of keys and values. Then fetch the key using the position of the value in the val_list . As key at any position N in  Python | Get values of particular key in list of dictionaries Sometimes, we may require a way in which we have to get all the values of specific key from a list of dictionary. This kind of problem has a lot of application in web development domain in which we sometimes have a json and require just to get single column from records.

How would I print the keys of all pairs of matching values in a Python , A regular Python dictionary can only hold one value for any given key. How can I get input several "keys" and "values" (for 3-4 items) within the loop in python​  Python provides one keys() method to get all keys from a python dictionary. Then we can iterate through the keys one by one and print out the value for each key. Then we can iterate through the keys one by one and print out the value for each key.

Python dictionary example to find keys with the same value, We will take all inputs from the user, i.e. the user will enter the key-value pairs for the dictionary and also the value. Python program : Before going  Using items() function, get the list of all key-value pairs of the dictionary. Store the list in value_to_find variable. Now, iterate all items in the list one by one using a ‘for loop’. For each item in the list, check if any value is equal to the user input value value_to_find. If yes, add the key for that value to the final result set.

Comments
  • make a recursive function x that searches every val for dog and sends every val that is dict to function x
  • non-generator version for good measure? Not efficient and Pythonic though! I'd liked to see a non-recursion solution for the sake of memory efficiency not a non-generator solution that makes it even worse!
  • @Kasramvd well, I had posted it before I saw you had already provided a solution, and perhaps I was too attached to it. I'm not sure an iterative solution would be necessary, honestly, if you are nesting more than 10 levels deep, you've got other problems