2

I have dictionary like this

my_dict={'0':['A','B','C'],'1':['D','E','F']}

How can I access the key using one of the value if value is a list ?

  • You should have read about [python's dict structure](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) first before coming here. – baduker Mar 20 '21 at 16:58
  • 1
    @baduker That dosen't seem to answer my question mate –  Mar 20 '21 at 17:00
  • 1
    And this should be on your reading list too [how much research effort is expected on SO](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – baduker Mar 20 '21 at 17:02
  • Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – baduker Mar 20 '21 at 17:03

1 Answers1

2

You could try this:

>>> def corresponding_key(val, dictionary):
        for k, v in dictionary.items():
            if val in v:
                return k

>>> corresponding_key("A", my_dict)
'0'
>>> corresponding_key("B", my_dict)
'0'
>>> corresponding_key("C", my_dict)
'0'
>>> corresponding_key("D", my_dict)
'1'
>>> corresponding_key("E", my_dict)
'1'
>>> corresponding_key("F", my_dict)
'1'
>>> 

However, in the case where a value is in multiple dictionary value lists, you can modify the function:

>>> def corresponding_keys(val, dictionary):
        keys = []
        for k, v in dictionary.items():
            if val in v:
                keys.append(k)
        return keys

Or, you could use list comprehension:

>>> val = "A"
>>> dictionary = my_dict
>>> [k for k, v in dictionary.items() if val in v]
['0']
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
  • Which one is best in performance ? (Just Curious) –  Mar 20 '21 at 17:47
  • @ConMan77 I would rank them (in order of best performance to least performance): **1, 3, 2**. I may be wrong, but here's my logic: Number 1 does not have to parse through every key-value pair, as it returns immediately once a match if found; Number 3 uses list comprehension, which is generally faster than function calling, but must iterate over every pair; Number 2 combines the worst of 1 and 3, where it is a function call and must iterate through each pair, plus the added memory taken by the list variable `keys`. – Jacob Lee Mar 20 '21 at 17:56