d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Python如何认识到它只需要从字典中读取密钥?key是一个特殊的关键字,还是仅仅是一个变量?
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Python如何认识到它只需要从字典中读取密钥?key是一个特殊的关键字,还是仅仅是一个变量?
当前回答
这将按升序值按排序顺序打印输出。
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只是一个变量,正如您所提到的,那么需要注意的是,当您在字典上运行“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不是一个变量,而是一个函数。
如果您正在寻找清晰直观的示例:
cat = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
print(key, ': ', value)
结果:
name: Snowy
color: White
age: 14
使用for..遍历字典时。。在..中-语法,它总是在键上迭代(值可以使用dictionary[key]访问)。
要迭代键值对,请使用以下命令:
对于Python 2中dict.iteritems()中的k,v对于Python 3中dict.items()中的k,v
对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))
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)