Created
April 2, 2020 04:58
-
-
Save AntiKnot/9174a060158880d2e48f962c94fec483 to your computer and use it in GitHub Desktop.
update dict in loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from copy import deepcopy | |
| d1 = {1: 1, 2: 2} | |
| def change_dict_in_loop(): | |
| d_copy = deepcopy(d1) | |
| for k, v in d1.items(): | |
| d_copy.pop(1, None) | |
| return d_copy | |
| if __name__ == '__main__': | |
| d = change_dict_in_loop() | |
| print(d) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
python的update操作会修改kv对在dict中的顺序,造成loop不能正确遍历。
《fluent python》 中给出过解释,hashtable实现会造成当dict大小变换的时候会扩充和缩小hashtable的size,从而造成对象info信息的修改,导致jump的时候顺序被修改。况且hashtable在定义上就没有顺序。