Merging duplicate keys in a list of dictionaries in python

  python

I’m currently trying to get this:

[{'2020-11-26': {'id': [94]}, {'id': [8889]}, {'id': [8872]}}, 
 {'2020-11-27': {'id': [8938]}}]

from these:

dates = {94: {'2020-11-26'}, 8872: {'2020-11-26'}, 8889: {'2020-11-26'}, 8938: {'2020-11-27'}}
ids = [94, 8889, 8872, 8938]

but when I run this list comprehension:

[{" ".join(dates[x]): {"id":[x]}} for x in ids]

I get this structure:

[{'2020-11-26': {'id': [94]}},
 {'2020-11-26': {'id': [8889]}},
 {'2020-11-26': {'id': [8872]}},
 {'2020-11-27': {'id': [8938]}}]

I cannot seem to be able to remove the duplicate key dates, I tried using defaultdict but I cannot seem to get it to work.

Source: Python Questions

LEAVE A COMMENT