0

I have a list of words that I want to organize in a dictionary according to the content of another list:

group_identifier = [1,2,1]
word_list = ['a', 'big', 'problem']
word_dict = dict.fromkeys([x for x in group_identifier], {'words': []})
for word, group in zip(word_list, group_identifier):
    word_dict[group]['words'].append(word)

print(word_dict)

I would like to get:

{1: {'words': ['a', 'problem']}, 2: {'words': ['big']}},

but I get:

{1: {'words': ['a', 'big', 'problem']}, 2: {'words': ['a', 'big', 'problem']}}

Help would be greatly appreciated!

Nicolas
  • 85
  • 2
  • 6
  • FYI, `[x for x in group_identifier]` is superfluous, just `group_identifier` would do the exact same thing. It’s already a list of items. – deceze Feb 23 '21 at 17:40
  • 1
    https://docs.python.org/3/library/stdtypes.html#dict.fromkeys - *fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.* – Razzle Shazl Feb 23 '21 at 17:47

1 Answers1

0

You only create one list object with {'words': []}. Use a list comprehension to initialize the dict:

word_dict = {k: {'words': []} for k in group_identifier}

This initializes an individual list for each key.

deceze
  • 510,633
  • 85
  • 743
  • 889