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是一个特殊的关键字,还是仅仅是一个变量?
当前回答
使用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)
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
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())。
要迭代键,使用my_dict.keys()会更慢,但效果更好。如果您尝试这样做:
for key in my_dict:
my_dict[key+"-1"] = my_dict[key]-1
它会创建一个运行时错误,因为在程序运行时您正在更改密钥。如果您绝对希望减少时间,请以my_dict方式使用for键,但您已收到警告。