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

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

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


当前回答

使用for..遍历字典时。。在..中-语法,它总是在键上迭代(值可以使用dictionary[key]访问)。

要迭代键值对,请使用以下命令:

对于Python 2中dict.iteritems()中的k,v对于Python 3中dict.items()中的k,v

其他回答

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)

使用for..遍历字典时。。在..中-语法,它总是在键上迭代(值可以使用dictionary[key]访问)。

要迭代键值对,请使用以下命令:

对于Python 2中dict.iteritems()中的k,v对于Python 3中dict.items()中的k,v

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

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进行迭代时,不按特定顺序遍历其键,如您所见:

(Python 3.6不再是这种情况,但请注意,它还不能保证行为。)

>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> list(d)
['y', 'x', 'z']
>>> d.keys()
['y', 'x', 'z']

例如,最好使用dict.items():

>>> d.items()
[('y', 2), ('x', 1), ('z', 3)]

这将提供元组列表。当您这样循环它们时,每个元组都会自动解压缩为k和v:

for k,v in d.items():
    print(k, 'corresponds to', v)

如果循环体只有几行,则在遍历dict时使用k和v作为变量名是非常常见的。对于更复杂的循环,最好使用更具描述性的名称:

for letter, number in d.items():
    print(letter, 'corresponds to', number)

养成使用格式字符串的习惯是个好主意:

for letter, number in d.items():
    print('{0} corresponds to {1}'.format(letter, number))

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

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

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