Reputation:
Hope to get the key from the value like the below.
d = {'key1': 'a', 'key2': 'b', 'key3': 'c'}
-> 'key1' in the case that value is 'a'
d2 = {'key1': ['a', 'b', 'c'], 'key2': ['d', 'e', 'f'], 'key3': ['g', 'h', 'i']}
-> 'key1' in the case that value is 'a'
However, I have a trouble to execute it when the dictionary has values that are list types.
How can I fix my current code?
Traceback (most recent call last):
File "sample.py", line 10, in <module>
key = [k for k, v in d2.items() if v == 'a'][0]
IndexError: list index out of range
d = {'key1': 'a', 'key2': 'b', 'key3': 'c'}
#get the key from the vakue
print(d.items())
key = [k for k, v in d.items() if v == 'a'][0]
print(key)
d2 = {'key1': ['a', 'b', 'c'], 'key2': ['d', 'e', 'f'], 'key3': ['g', 'h', 'i']}
print(d2.items())
key = [k for k, v in d2.items() if v == 'a'][0]
print(key)
$ python sample.py
[('key3', 'c'), ('key2', 'b'), ('key1', 'a')]
key1
[('key3', ['g', 'h', 'i']), ('key2', ['d', 'e', 'f']), ('key1', ['a', 'b', 'c'])]
Upvotes: 0
Views: 70
Reputation: 87
d = {'key1':['a','b','c'], 'key2': ['a', 'd', 'e']}
key_list = [k for k, v in d.items() if 'a' in v] # For all the keys having 'a' in value.
>>> key_list
['key1', 'key2']
key = [k for k, v in d.items() if 'a' in v][0] #Get Only one key by specifying index as [0] from key_list.
>>> key
'key1'
Upvotes: 0
Reputation: 9580
The problem is you are matching 'a'
with the complete list so the list generated by list comprehension is an empty list so you get index error when you try to access the element of the list at the 0
th index.
You need to use in
keyword for the second scenario:
You could also use the generator expression if you are sure that the key exists only once:
d2 = {'key1': ['a', 'b', 'c'], 'key2': ['d', 'e', 'f'], 'key3': ['g', 'h', 'i']}
print(d2.items())
key = next(k for k, v in d2.items() if 'a' in v)
print(key)
Upvotes: 1
Reputation: 176
If you simply want to take for example the first item in the list ['a','b','c']
(which is the value of the key key1
of your d2 dictionary in your case) you can do:
print(d2['key1' # your key name][0 # the index of the value list])
The output is:
>>> b
Upvotes: 0
Reputation: 14263
In the second case your list comprehension yields empty list, so index 0 does not exists and you get IndexError. You want to check 'a' in v
:
d2 = {'key1': ['a', 'b', 'c'], 'key2': ['d', 'e', 'f'], 'key3': ['g', 'h', 'i']}
key = [k for k, v in d2.items() if 'a' in v][0]
Upvotes: 1