Oli*_*ett 1 python dictionary loops
我有一本字典,我想将该字典中的所有键更改为另一个字典中的值.
例如:
X = {"apple" : 42}
Y = {"apple" : "Apples"}
Run Code Online (Sandbox Code Playgroud)
转换后:
快译通 X = {"Apples" : 42}
def convert(items, ID):
for key, value in items.items():
for keys, values in ID.items():
if keys == key:
key = values
return items
Run Code Online (Sandbox Code Playgroud)
所以我已经编写了上面的代码来执行此操作,但是在执行此函数后,我打印字典并且键没有更改.
这是因为您要为局部变量分配新值,而不是为字典键分配新值.
但是,为了获得所需的结果,我建议做其他人已经建议的内容并创建一个新字典,因为您的密钥与任何现有字典不对齐:
如果你想这样做,你必须通过字典赋值显式设置值:
def convert(X, Y):
new_dict = {}
for x_key, x_value in X.items():
for y_key, y_value in Y.items():
if x_key == y_key:
new_dict[y_value] = x_value
return new_dict
Run Code Online (Sandbox Code Playgroud)