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

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

Getting error while popping in dictionary python

问题

以下是翻译好的部分:

我有一个字典

price={'10MAR23': 113.49999999999999,
 '3MAR23': 19.10000000000001,
 '25FEB23': 19.100000000000012,
 '28APR23': 3.5,
 '26FEB23': 0.4,
 '31MAR23': 27.5,
 '17MAR23': 3.1}

我想用格式为%d%m%y的相应日期替换键

100323
030323
250223
280423
260223
310323
170323

以下代码可以实现这一点

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

但出现以下错误

ValueError: time data '030323' does not match format '%d%b%y'
英文:

I have a dictionary

price={'10MAR23': 113.49999999999999,
 '3MAR23': 19.10000000000001,
 '25FEB23': 19.100000000000012,
 '28APR23': 3.5,
 '26FEB23': 0.4,
 '31MAR23': 27.5,
 '17MAR23': 3.1}

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

100323
030323
250223
280423
260223
310323
170323

The following code does that,

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

but getting error like

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

答案1

得分: 3

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

price = {'10MAR23': 113.49999999999999,
         '3MAR23': 19.10000000000001,
         '25FEB23': 19.100000000000012,
         '28APR23': 3.5,
         '26FEB23': 0.4,
         '31MAR23': 27.5,
         '17MAR23': 3.1}

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

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

price = {datetime.datetime.strptime(k, '%d%b%y').strftime('%d%m%y'): v 
         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:

price = {'10MAR23': 113.49999999999999,
         '3MAR23': 19.10000000000001,
         '25FEB23': 19.100000000000012,
         '28APR23': 3.5,
         '26FEB23': 0.4,
         '31MAR23': 27.5,
         '17MAR23': 3.1}

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

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

price = {datetime.datetime.strptime(k, '%d%b%y').strftime('%d%m%y'): v 
         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:

确定