d = {'x': 1, 'y': 2, 'z': 3}

for key in d:
    print(key, 'corresponds to', d[key])

Python如何认识到它只需要从字典中读取密钥?key是一个特殊的关键字,还是仅仅是一个变量?


当前回答

让我们开门见山。如果单词key只是一个变量,正如您所提到的,那么需要注意的是,当您在字典上运行“FOR LOOP”时,它只运行“key”,而忽略“value”。

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print (key, 'corresponds to', d[key])

不妨尝试一下:

d = {'x': 1, 'y': 2, 'z': 3} 
for i in d:
    print (i, 'corresponds to', d[i])

但如果使用以下函数:

d = {'x': 1, 'y': 2, 'z': 3}
print(d.keys())

在上面的例子中,keys不是一个变量,而是一个函数。

其他回答

这将按升序值按排序顺序打印输出。

d = {'x': 3, 'y': 1, 'z': 2}

def by_value(item):
    return item[1]

for key, value in sorted(d.items(), key=by_value):
    print(key, '->', value)

输出:

y->1z->2x->3

key只是一个变量。

对于Python2.X:

>>> d = {'x': 1, 'y': 2, 'z': 3} 
>>> for my_var in d:
>>>     print my_var, 'corresponds to', d[my_var]

x corresponds to 1
y corresponds to 2
z corresponds to 3

…或更好,

d = {'x': 1, 'y': 2, 'z': 3} 

for the_key, the_value in d.iteritems():
    print the_key, 'corresponds to', the_value

对于Python3.X:

d = {'x': 1, 'y': 2, 'z': 3} 

for the_key, the_value in d.items():
    print(the_key, 'corresponds to', the_value)

对于通过字典进行迭代,可以使用以下代码。

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
    print(key)

#To Iterate over the values
for value in dictionary.values():
    print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
    print(key,'\t', value)

我有一个用例,我必须遍历dict以获得键、值对以及指示我所在位置的索引。我是这样做的:

d = {'x': 1, 'y': 2, 'z': 3} 
for i, (key, value) in enumerate(d.items()):
   print(i, key, value)

请注意,键、值周围的括号很重要,如果没有它们,您将得到ValueError“没有足够的值来解包”。

这是一个非常常见的循环习惯用法。in是运算符。有关何时在dict中使用key以及何时必须在dict.keys()中使用key的信息,请参阅David Goodger的惯用Python文章(存档副本)。