我有一个OrderedDicts的列表,格式如下:
[OrderedDict([('id', 1), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', None)]), OrderedDict([('id', 2), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', 1)])]
我想操作上面的列表并产生如下形式的输出:
[
{
"number": 0,
"created_at": "15-04-2022 10:27:37",
"dr_notice_period": 15,
"dr_duration": 30,
"dr_request": 1000.0
},
{
"number": 1,
"created_at": "15-04-2022 10:27:37",
"dr_notice_period": 15,
"dr_duration": 30,
"dr_request": 1000.0
}
]
我现在所做的是使用两个for循环遍历所有元素并创建输出列表:
output = []
for i in range(len(input)):
temp = {}
for key, value in input[i].items():
temp["number"] = i
if key == "dr_notice_period":
temp[key] = value
if key == "dr_duration":
temp[key] = value
if key == "dr_request":
temp[key] = value
if key == "created_at":
temp[key] = value
output.append(temp)
有没有更好更有效的方法来避免嵌套的for循环?
使用字典的update
方法
lst = [OrderedDict([('id', 1), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', None)]), OrderedDict([('id', 2), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', 1)])]
output = []
for i, ordict in enumerate(lst):
item = {'number': i}
item.update(ordict)
item.pop('id')
output.append(item)
print(output)
如果您不需要将'id'更改为'number'及其值,则更简单:
output = [dict(item) for item in lst]
print(output)
我可以提出以下解决方案:
from collections import OrderedDict
l = [OrderedDict([('id', 1), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', None)]),
OrderedDict([('id', 2), ('created_at', '15-04-2022 10:27:37'), ('dr_notice_period', 15), ('dr_duration', 30), ('dr_request', 1000.0), ('user_id_event', 1)])]
crits = ["dr_notice_period", "dr_duration", "dr_request", "created_at"] # extendable
temp = [dict({"number":num}, **{k:v for k,v in i.items() if k in crits})
for num, i in enumerate(l, start=1)]
from pprint import pprint
pprint(temp)
结果:
[{'created_at': '15-04-2022 10:27:37',
'dr_duration': 30,
'dr_notice_period': 15,
'dr_request': 1000.0,
'number': 1},
{'created_at': '15-04-2022 10:27:37',
'dr_duration': 30,
'dr_notice_period': 15,
'dr_request': 1000.0,
'number': 2}]