I have two dict as shown below. I am on Python 2.7.
entries_per_day = [ {"time": "October 1", "entries": "5" },
{"time": "October 2", "entries": "3" },
{"time": "October 3", "entries": "1" },
{"time": "October 4", "entries": "0" },
{"time": "October 5", "entries": "23" }]
views_per_day = [ {"time": "October 1", "views": "9" },
{"time": "October 2", "views": "3" },
{"time": "October 3", "views": "5" },
{"time": "October 4", "views": "6" },
{"time": "October 5", "views": "32" }]
How can I merger the two dictionaries into a 3rd so that the output looks like this:
area_chart_data = [ {"time": "October 1", "entries": "5", "views": "9" },
{"time": "October 2", "entries": "3", "views": "3" },
{"time": "October 3", "entries": "1", "views": "5" },
{"time": "October 4", "entries": "0", "views": "6" },
{"time": "October 5", "entries": "23", "views": "32" }]
I want the "entries" and "views" key-value pairs to be in the same data segment as the date they were originally with.
Since the dict entries seem to match, just zip
both lists and update one dict with the second one, then insert in a list.
area_chart_data = []
for e,v in zip(entries_per_day,views_per_day):
e.update(v)
area_chart_data.append(e)
print(area_chart_data)
result:
[{'views': '9', 'time': 'October 1', 'entries': '5'}, {'views': '3', 'time': 'October 2', 'entries': '3'}, {'views': '5', 'time': 'October 3', 'entries': '1'}, {'views': '6', 'time': 'October 4', 'entries': '0'}, {'views': '32', 'time': 'October 5', 'entries': '23'}]
it changes the first list. If you don't want that, you have to do e = e.copy()
before the update
EDIT: one-liner using "dict addition" as stated in this Q&A:
area_chart_data = [dict(e, **v) for e,v in zip(entries_per_day,views_per_day)]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments