在Python中弹出字典时出现错误。

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

Getting error while popping in dictionary python

问题

以下是翻译好的部分:

  1. 我有一个字典
  2. price={'10MAR23': 113.49999999999999,
  3. '3MAR23': 19.10000000000001,
  4. '25FEB23': 19.100000000000012,
  5. '28APR23': 3.5,
  6. '26FEB23': 0.4,
  7. '31MAR23': 27.5,
  8. '17MAR23': 3.1}
  9. 我想用格式为%d%m%y的相应日期替换键
  10. 100323
  11. 030323
  12. 250223
  13. 280423
  14. 260223
  15. 310323
  16. 170323
  17. 以下代码可以实现这一点
  18. for i in price:
  19. new_key=datetime.datetime.strptime(i,'%d%b%y').strftime('%d%m%y')
  20. price[new_key]=price.pop(i)
  21. 但出现以下错误
  22. ValueError: time data '030323' does not match format '%d%b%y'
英文:

I have a dictionary

  1. price={'10MAR23': 113.49999999999999,
  2. '3MAR23': 19.10000000000001,
  3. '25FEB23': 19.100000000000012,
  4. '28APR23': 3.5,
  5. '26FEB23': 0.4,
  6. '31MAR23': 27.5,
  7. '17MAR23': 3.1}

I want to replace the keys with respective dates with format as %d%m%y like

  1. 100323
  2. 030323
  3. 250223
  4. 280423
  5. 260223
  6. 310323
  7. 170323

The following code does that,

  1. for i in price:
  2. new_key=datetime.datetime.strptime(i,'%d%b%y').strftime('%d%m%y')
  3. price[new_key]=price.pop(i)

but getting error like

  1. ValueError: time data '030323' does not match format '%d%b%y'

答案1

得分: 3

这是因为您在循环时同时修改了price的键。您可以通过在执行循环之前复制字典来避免这种情况,如下所示:

  1. price = {'10MAR23': 113.49999999999999,
  2. '3MAR23': 19.10000000000001,
  3. '25FEB23': 19.100000000000012,
  4. '28APR23': 3.5,
  5. '26FEB23': 0.4,
  6. '31MAR23': 27.5,
  7. '17MAR23': 3.1}
  8. for i in dict(price):
  9. new_key = datetime.datetime.strptime(i, '%d%b%y').strftime('%d%m%y')
  10. price[new_key] = price.pop(i)

或者,您可以使用字典推导式从旧字典中创建一个新字典:

  1. price = {datetime.datetime.strptime(k, '%d%b%y').strftime('%d%m%y'): v
  2. for k, v in price.items()}
英文:

This happens because you are looping over price while modifying its keys at the same time. You can avoid that by copying the dictionary before performing the loop, with for i in dict(price):, as so:

  1. price = {'10MAR23': 113.49999999999999,
  2. '3MAR23': 19.10000000000001,
  3. '25FEB23': 19.100000000000012,
  4. '28APR23': 3.5,
  5. '26FEB23': 0.4,
  6. '31MAR23': 27.5,
  7. '17MAR23': 3.1}
  8. for i in dict(price):
  9. new_key = datetime.datetime.strptime(i,'%d%b%y').strftime('%d%m%y')
  10. price[new_key] = price.pop(i)

Alternatively, you can create a new dictionary from the old one with a dictionary comprehension

  1. price = {datetime.datetime.strptime(k, '%d%b%y').strftime('%d%m%y'): v
  2. for k, v in price.items()}

huangapple
  • 本文由 发表于 2023年2月24日 16:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554382.html
匿名

发表评论

匿名网友

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

确定