英文:
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()}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论