相关疑难解决方法(0)

如何使用d.items()更改for循环中的所有字典键?

我想帮助理解为什么这段代码没有按预期工作.

如果想要更改字典的键但保留值,他/她可能会使用:

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)

python dictionary for-loop python-3.x

12
推荐指数
2
解决办法
1万
查看次数

标签 统计

dictionary ×1

for-loop ×1

python ×1

python-3.x ×1