Get the index of the values in python dict

say I have this dict with the values and I want to get the index of each element of the values for either key. I have tried different things but nothing has worked yet. Any help

my_dict = {
    "Up": [1,2,3,4],
    "Down": [5,6]
}

I tried this


indx_val= [[y for y in x] for x in my_dict.values() if my_dict.keys() == "Up"]

Edit I tried this too: 
my_keys = ' '.join([key for key in my_dict])

indx_val= [[y for y in x] for x in my_dict.values() if my_keys == "Up"]

expected output

[[0,1,2,3]]

Both using my_dict.keys() and my_keys try to compare single key to all keys, comparing them like that won’t work. Have you tried items() method of dictionary? It iterates through dictionary returning (key, value) pair tuple in each iteration. It will easier allow further operations on value, if key matches wanted one.

Allow me to introduce you to Python’s enumerate() function.

So for your case:

my_indices = [
    [i for i, _ in enumerate(val)]
    for val in my_dict.values()
]
[[0, 1, 2, 3], [0, 1]]

I have trouble understanding your goal.
Your expected output just looks like [ my_dict["Up"] ] and hence doesn’t need any fancy list-comprehension you do there.
If you want the actual indices… well those go from 0 to the length of the list, so that’s:
[ i for i in range( len( my_dict["Up"] ) ) ]

Also one thing to REALLY test out is how multiple for-loops and/or if-clauses work in a list-comprehension.

This is how I exactly wanted but was not able to get the right syntax. Other answer are helpful too so thanks everyone.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.