如何在Python的循环中替换字典中的键

huangapple go评论60阅读模式
英文:

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_"))

huangapple
  • 本文由 发表于 2023年2月17日 23:49:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定