Your question is ambiguous, as pointed out by Peter DeGlopper:
What result are you expecting if multiple keys have the target value? Does it differ if the keys are in different dictionaries?
However, if for example you want a list of 2-tuples (i, k)
– where i
is the index (in the list) of the dictionary where the value is found, and k
is the key associated with the value – the following works:
def index_keys(data, value):
return [(i, k) for i, d in enumerate(data) for k, v in d.items() if v == value]
Examples:
>>> list1 = [
... {'a':1,'b':2,'c':3},
... {'d':4,'e':5,'f':6},
... {'g':7,'h':8,'i':9}
... ]
>>> index_keys(list1, 5)
[(1, 'e')]
>>> list1[1]['e'] == 5
True
>>> list2 = [
... {'a': 1, 'b': 2, 'c': 3, 'd': 4},
... {'w': 2, 'x': 4, 'y': 6, 'z': 8},
... {'a': 6, 'b': 6, 'y': 6, 'z': 8}
... ]
>>> index_keys(list2, 2)
[(0, 'b'), (1, 'w')]
>>> index_keys(list2, 8)
[(1, 'z'), (2, 'z')]
>>> index_keys(list2, 6)
[(1, 'y'), (2, 'a'), (2, 'y'), (2, 'b')]