1

I have a dataset that, among other things, contains the creation date. I turn the date into months and generate a dict with the month number as the key and an empty list:

{8: [], 7: []}

Then I try to add the rest of the data on the key to this empty list, but all the data is added to the list, not just the desired key. This is what I get in the output:

{8: [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8], 7: [7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8]}

But, it should be like this

{8: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8], 7: [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]}

What i'm doing wrong? My code is...

    group_keys = []
    for e in data:
        group_keys.append(e.get('start_date').month)
    
    group_keys = dict.fromkeys(set(group_keys), [])
    print(group_keys)
    for e in data:
        month = e.get('start_date').month
        group_keys[month].append(month)
    print(group_keys)
matszwecja
  • 6,357
  • 2
  • 10
  • 17
Nataly Firstova
  • 661
  • 1
  • 5
  • 12

1 Answers1

2

All of the entries in group_keys are pointing to the same list. Try using a dictionary comprehension to create group_keys

group_keys = {x:[] for x in set(group_keys)}