Skip to content
Advertisement

python need to iterate a list over a list of dicts

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]

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement