Home > other >  Find a better way to iterate over a list of OrderedDicts
Find a better way to iterate over a list of OrderedDicts

Time:04-23

I have a list of OrderedDicts in the following form:

[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)])]

I want to manipulate the above list and produce an output of the following form:

[
    {
        "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
    }
]

What I am doing right now is to use two for loops to iterate over all the elements and create the output list:

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)

Is there a better and more efficient way to do it by avoiding the nested for loops?

CodePudding user response:

Use update method of dictionary.

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)

If you don't need to change 'id' to 'number' and its value, it is more simple:

output = [dict(item) for item in lst]
print(output)

CodePudding user response:

I could propose the following solution :

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)

Result:

[{'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}]
  • Related