Reputation: 131
I have this 2 list of dictionaries
a = [{'Month': 'Sep 2021', 'Like': 6}, {'Month': 'Oct 2021', 'Like': 7}]
b = [{'Month': 'Aug 2021', 'View': 20}, {'Month': 'Oct 2021', 'View': 8}]
I want this result
c = [{'Month': 'Aug 2021', 'Like': 0, 'View': 20},
{'Month': 'Sep 2021', 'Like': 6, 'View': 0},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}]
I tried this one
d = defaultdict(dict)
for l in (a, b):
for elem in l:
d[elem['Month']].update(elem)
c = d.values()
but the result is this
dict_values([{'Month': 'Aug 2021', 'View': 20},
{'Month': 'Sept 2021', 'Like': 6},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}])
How can I add 0 if there is no value?
Thanks!
Upvotes: 2
Views: 79
Reputation: 131
As per @kaya3 in the comments, I get the result by using
d = defaultdict(lambda: {'Like': 0, 'View': 0})
Upvotes: 3