我想帮助理解为什么这段代码没有按预期工作.
如果想要更改字典的键但保留值,他/她可能会使用:
d[new_key] = d.pop[old_key]
Run Code Online (Sandbox Code Playgroud)
我想修改所有键(并保持值到位),但下面的代码跳过某些行 - ("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)
Run Code Online (Sandbox Code Playgroud)