【发布时间】:2018-02-03 06:43:59
【问题描述】:
我需要一些帮助来理解为什么这段代码没有按预期工作。
如果一个人想改变字典的键但保留值,他/她可能会使用:
d[new_key] = d.pop[old_key]
我想修改所有键(并保留值),但下面的代码跳过某些行 - ("col2") 保持不变。是不是因为字典是无序的,而我一直在更改其中的值?
如何在不创建新字典的情况下更改键并保留值?
import time
import pprint
name_dict = {"col1": 973, "col2": "1452 29th Street",
"col3": "Here is a value", "col4" : "Here is another value",
"col5" : "NULL", "col6": "Scottsdale",
"col7": "N/A", "col8" : "41.5946922",
"col9": "Building", "col10" : "Commercial"}
for k, v in name_dict.items():
print("This is the key: '%s' and this is the value '%s'\n" % (k, v) )
new_key = input("Please enter a new key: ")
name_dict[new_key] = name_dict.pop(k)
time.sleep(4)
pprint.pprint(name_dict)
【问题讨论】:
-
字典是无序的 - 完全正确
-
可以...
new_dict = {input('Enter new key for {}'.format(k)): v for k, v in name_dict.items()}... ? -
@JonClements,不创建新字典
-
在迭代时修改往往会导致意外行为,你为什么不想要一个新的
dict,是内存问题吗? -
@RomanPerekhrest 啊,好点......但仍然......除非它是纯粹的理论或绝对要求 - 这无疑是最简单的......
标签: python python-3.x dictionary for-loop