英文:
how to replace a key in dict python for loop
问题
for key, value in d.items():
new_key = re.sub(r'given_', '', key)
if new_key != key:
d[new_key] = d.pop(key)
英文:
d={"given_age":"30","given_weight":"160","given_height":6}
want to remove "given_"
from each of the key,
for key,value in d.items():
new_key=re.sub(r'given_','',key)
if new_key!=key:
d[new_key]=d.pop(key)
getting below error, my intention is to change the key only, why does it complain?
RuntimeError: dictionary keys changed during iteration
答案1
得分: 5
尽量不要在迭代过程中修改集合。在这里使用字典推导式。
res = {re.sub('given_', '', k): v for k, v in d.items()}
英文:
It is best not to modify collections when iterating over them. Use a dict comprehension here instead.
res = {re.sub('given_','',k) : v for k, v in d.items()}
答案2
得分: 1
你也可以使用 `str.replace()` 与字典解析
d = {"given_age": "30", "given_weight": "160", "given_height": 6}
{key.replace('given_', ''): value for key, value in d.items()}
# {'age': '30', 'weight': '160', 'height': 6}
根据 @CrazyChucky 的建议进行编辑
{key.removeprefix('given_'): value for key, value in d.items()}
# {'age': '30', 'weight': '160', 'height': 6}
英文:
You can also use str.replace()
with dict comprehensiomn
d={"given_age":"30","given_weight":"160","given_height":6}
{key.replace('given_', '') : value for key, value in d.items()}
#{'age': '30', 'weight': '160', 'height': 6}
Edit as suggested by @CrazyChucky
{key.removeprefix('given_') : value for key, value in d.items()}
#{'age': '30', 'weight': '160', 'height': 6}
答案3
得分: 0
如果你需要在原地执行此操作,并且只更改具有“given_”前缀的键,你可以使用update方法:
d.update((k[6:], d.pop(k)) for k in d if k.startswith("given_"))
英文:
If you need to do this "in-place" and only change the keys that have the "given_" prefix, you could use the update method:
d.update((k[6:],d.pop(k)) for k in d if k.startswith("given_"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论