Ad

Python: Obtaining Index Of An Element Within A Value List Of A Dictionary

- 1 answer

I have a dictionary with key:value list pairings, and I intend to find the index of the value list that contains the desired element.

E.g., if the dictionary is:

my_dict = {"key1":['v1'], "key2":None, "key3":['v2','v3'], "key4":['v4','v5','v6']}

Then, given element 'v2' I should be able to get index 2.

For a value list with one element, the index can be obtained with: list(my_dict.values()).index(['v1']) , however this approach does not work with lists containing multiple elements.

Using for loop, it can be obtained via:

for key, value in my_dict.items():
  if value is None:
    continue
  if 'v2' in value:
    print (list(my_dict.keys()).index(key))

Is there a neater (pythonic) way to obtain the same?

Ad

Answer

Don't know if it's the best solution but this works:

value = 'v2'
list(map(lambda x : value in x, list(map(lambda x : x[1] or [], list(my_dict.items()))))).index(True)
Ad
source: stackoverflow.com
Ad