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是一个特殊的关键字,还是仅仅是一个变量?
当前回答
key只是一个变量名。
for key in d:
将简单地遍历字典中的键,而不是键和值。要循环键和值,可以使用以下方法:
对于Python 3.x:
for key, value in d.items():
对于Python 2.x:
for key, value in d.iteritems():
为了测试自己,将单词key改为poop。
在Python3.x中,itertists()被替换为简单的items(),它返回一个由dict支持的类似集合的视图,就像itertists(),但更好。这在2.7中也可用作viewitems()。
操作items()将同时适用于2和3,但在2中,它将返回字典(键、值)对的列表,这不会反映items(()调用后对字典的更改。如果您想要3.x中的2.x行为,可以调用list(d.items())。
其他回答
对于通过字典进行迭代,可以使用以下代码。
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)
使用for..遍历字典时。。在..中-语法,它总是在键上迭代(值可以使用dictionary[key]访问)。
要迭代键值对,请使用以下命令:
对于Python 2中dict.iteritems()中的k,v对于Python 3中dict.items()中的k,v
这是一个非常常见的循环习惯用法。in是运算符。有关何时在dict中使用key以及何时必须在dict.keys()中使用key的信息,请参阅David Goodger的惯用Python文章(存档副本)。
key只是一个变量名。
for key in d:
将简单地遍历字典中的键,而不是键和值。要循环键和值,可以使用以下方法:
对于Python 3.x:
for key, value in d.items():
对于Python 2.x:
for key, value in d.iteritems():
为了测试自己,将单词key改为poop。
在Python3.x中,itertists()被替换为简单的items(),它返回一个由dict支持的类似集合的视图,就像itertists(),但更好。这在2.7中也可用作viewitems()。
操作items()将同时适用于2和3,但在2中,它将返回字典(键、值)对的列表,这不会反映items(()调用后对字典的更改。如果您想要3.x中的2.x行为,可以调用list(d.items())。
这将按升序值按排序顺序打印输出。
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