例如,假设我们有以下字典:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}给定某个键的值,如何打印该键?
print(dictionary.get('A')) #This will print 4你怎么能倒着做呢?即,不是通过引用键来获得值,而是通过引用值来获得键。
发布于 2013-04-03 18:16:52
我不相信有办法做到这一点。这不是字典的用法...取而代之的是,你必须做类似的事情。
for key, value in dictionary.items():
if 4 == value:
print key发布于 2018-11-15 09:29:42
在Python 3中:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])输出:
Y发布于 2013-04-03 18:20:29
字典的组织方式为: key -> value
如果您尝试转到: value -> key
然后你会有一些问题;重复的,有时一个字典保存着你不想作为键的大的(或不可散列的)对象。
但是,如果您仍然希望这样做,您可以通过迭代dicts键和值并按如下方式匹配它们来轻松地完成此操作:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b正如注释中所指出的,整个事情可以写成一个生成器表达式:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)Python版本注意:在Python 3+中,可以使用dict.items()而不是dict.iteritems()
https://stackoverflow.com/questions/15784590
复制相似问题