Home > OS >  python need to iterate a list over a list of dicts
python need to iterate a list over a list of dicts

Time:12-01

a=['May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February']

b=[ {'actualscore1': 550, 'forecastedScore1': 33, 'unit': 'u2', 'account': 'a2', 'domain': 'd2', 'location': 'l2', 'year': 2021, 'month': 'October'},
{'actualscore1': 550, 'forecastedScore1': 34, 'unit': 'u1', 'account': 'A1', 'domain': 'd1', 'location': 'l1', 'year': 2021, 'month': 'November'}]

python need to iterate a list over a list of dicts

I need to iterate the list a over a list of dict b whether the value present or not. If present take some values from b and if not input as 0 for the months till september it should show as 0 and for december,jan and feb its should show 0

my output should be

output=[0,0,0,0,0,{'actualscore1': 550, 'forecastedScore1': 33,'month': 'October'},{'actualscore1': 550, 'forecastedScore1': 34,'month': 'November'},0,0,0]

CodePudding user response:

An approach using list comprehension:

keys = ['actualscore1', 'forecastedScore1', 'month'] # keys to extract
output = [next(({k: dct[k] for k in keys} for dct in b if dct['month'] == month), 0) for month in a]
print(output)
# [0, 0, 0, 0, 0, {'actualscore1': 550, 'forecastedScore1': 33, 'month': 'October'}, {'actualscore1': 550, 'forecastedScore1': 34, 'month': 'November'}, 0, 0, 0]

CodePudding user response:

Just loop over your data structures and get the data you need out of them:

output = []
for month in a:
    for d in b:
        if d["month"] == month:
            output.append({
                "actualscore1": d["actualscore1"], 
                "forecastedScore1": d["forecastedScore1"],
                "month": month,
            })
            break
    else:
        output.append(0)

CodePudding user response:

You can do it in one-liner like:

output = [next((d for d in b if month==d['month']), 0) for month in a]
  • Related