[英]How to get the key from the value on the dictionary whose values are list type
希望从下面的值中获取密钥。
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'
但是,当字典具有列表类型的值时,我很难执行它。
如何修复我当前的代码?
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'])]
在第二种情况下,您的列表理解产生空列表,因此索引 0 不存在并且您得到 IndexError。 您想检查'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]
问题是您将'a'
与完整列表匹配,因此列表理解生成的列表是一个空列表,因此当您尝试访问第0
个索引处的列表元素时会出现索引错误。
您需要在第二种情况下使用in
关键字:
如果您确定密钥只存在一次,您也可以使用生成器表达式:
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)
如果您只是想以列表中的第一项为例['a','b','c']
(在您的情况下,这是 d2 字典的键key1
的值),您可以执行以下操作: print(d2['key1' # your key name][0 # the index of the value list])
output 是: >>> b
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.