[英]How to get a key among the several values?
I would like to find the key from one value. 我想从一个值中找到关键。 But, a key has several values. 但是,键具有多个值。
I can't find the key by using the typical way to find the key from the value. 我无法通过使用从值中查找键的典型方法来查找键。
I already tried dict.items() and dict.iterms() instead of dict.iteritems() 我已经尝试了dict.items()和dict.iterms()而不是dict.iteritems()
But doesn't work. 但是不起作用。
dict = {'key1': ["value1", "value2"],
'key2': ["value3", "value4"] }
l = list()
for k, v in dict.iteritems():
if 'value3' in v:
l.append(k)
print(l)
I like to get the key from one value. 我喜欢从一个值中获取密钥。 For example, if I put 'value3' then print 'key2' 例如,如果我输入“ value3”,则打印“ key2”
dict.items()
definitely should work. dict.items()
绝对可以工作。
>>> foo = {'a': 'A', 'b': 'B'}
>>> foo.items()
dict_items([('a', 'A'), ('b', 'B')])
>>> for k, v in foo.items():
... print(k, v)
...
a A
b B
Avoid the keyword dict
to name your dictionary. 避免使用关键字dict
为字典命名。
You can reverse the dict key -> values
to a dict value -> key
: 您可以将dict key -> values
反转为dict value -> key
:
>>> d = {'key1': ["value1", "value2"], 'key2': ["value3", "value4"] }
>>> e = {v: k for k, vs in d.items() for v in vs}
>>> e
{'value1': 'key1', 'value2': 'key1', 'value3': 'key2', 'value4': 'key2'}
>>> e['value3']
'key2'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.