1

Let's say I have:

ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))

now, I know that by doing

list(dicio.keys())[list(dicio.values()).index('a')]

It returns <id>. But let's say that you only had one value associated per key, so

val = [['a', 'b', 'c'], 'b', '1+1']

How could I get <var> without listing ['a', 'b', 'c']? Thank you.

Vitor L.
  • 31
  • 3

1 Answers1

0

Just replace "a" value by the list ['a', 'b', 'c']:

print(list(dicio.keys())[list(dicio.values()).index(['a', 'b', 'c'])])

You will get as output the value associated with the index you inserted before:

<var>

Or you can use list comprehension to traverse the list of dict values:

ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))

selectedVal = list(i for i in list(dicio.values()) if "a" in i)[0]
print(list(dicio.keys())[val.index(selectedVal)])

Which outputs the same as the previous solution.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31