YXH*_*YXH 13 python dictionary
我希望在字典中弹出所有大值及其键,并保持最小值.这是我的计划的一部分
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
dictionary.pop(key)
print (dictionary)
Run Code Online (Sandbox Code Playgroud)
结果如何
RuntimeError: dictionary changed size during iteration
Run Code Online (Sandbox Code Playgroud)
我怎样才能避免这个错误?
Xb7*_*kjb 12
在Python3中,尝试
for key in list(dict.keys()):
if condition:
matched
del dict[key]
Run Code Online (Sandbox Code Playgroud)
循环dict以更新其密钥时,还应注意以下事项:
代码1:
keyPrefix = ‘keyA’
for key, value in Dict.items():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Run Code Online (Sandbox Code Playgroud)
代码2:
keyPrefix = ‘keyA’
for key, value in Dict.keys():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Run Code Online (Sandbox Code Playgroud)
code1/code2的结果是:
{‘keyA/keyA/keyB’ : ”, ‘keyA/keyA/keyA’: ”}
Run Code Online (Sandbox Code Playgroud)
我解决这个意外结果的方法:
Dict = {‘/’.join([keyPrefix, key]): value for key, value in Dict.items()}
Run Code Online (Sandbox Code Playgroud)
链接:https://hanbaobao2005.wordpress.com/2016/07/21/loop-a-dict-to-update-key/
如果您正在寻找字典中的最小值,您可以这样做:
min(dictionary.values())
Run Code Online (Sandbox Code Playgroud)
如果你不能使用min,你可以使用sorted:
sorted(dictionary.values())[0]
Run Code Online (Sandbox Code Playgroud)
在旁注中,您遇到的原因Runtime Error
是在内部循环中您修改了外部循环所基于的迭代器.当pop
外部循环尚未到达的条目和外部迭代器到达它时,它会尝试访问已删除的元素,从而导致错误.
如果你试图在Python 2.7(而不是3.x)上执行你的代码,你实际上会得到一个Key Error
.
如果你想修改迭代基于其在循环中的迭代器,你应该使用一个深拷贝它.
您可以使用copy.deepcopy制作原始字典的副本,在更改原始字典时循环复制.
from copy import deepcopy
d=dict()
for i in range(5):
d[i]=str(i)
k=deepcopy(d)
d[2]="22"
print(k[2])
#The result will be 2.
Run Code Online (Sandbox Code Playgroud)
你的问题是在你正在改变的事情上重复.