user13354595
user13354595

Reputation:

Get Key from a Value (Where value is in a list)

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 ?

Upvotes: 2

Views: 3117

Answers (1)

Jacob Lee
Jacob Lee

Reputation: 4670

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']

Upvotes: 2

Related Questions