Vas*_* De -1 python dictionary python-3.x
假设我们有这本字典:
thisdict = {
"brand": ["Ford","Renault", "Nissan"],
"Ford": ["red", "blue", "green"]
}
Run Code Online (Sandbox Code Playgroud)
当我将“Ford”键值更改为“droF”时,我希望它也在品牌列表中更改,反之亦然,如下所示:
thisdict = {
"brand": ["droF","Renault", "Nissan"],
"droF": ["red", "blue", "green"]
}
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
使用修改键和值的字典理解:
replacements = {
"Ford": "droF"
}
def modify(x):
# if it's in the dict, return the value in the dict
# otherwise default to itself
return replacements.get(x, x)
thisdict = {
"brand": ["Ford","Renault", "Nissan"],
"Ford": ["red", "blue", "green"]
}
modified = {
modify(k): [modify(x) for x in v] for k, v in thisdict.items()
}
print(modified)
# {'brand': ['droF', 'Renault', 'Nissan'], 'droF': ['red', 'blue', 'green']}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |