0

I have a dictionary that contains a list:

d = {'A': [1, 2, 3], 'B': 'hello'}

I want to unpack it in a list of dictionaries like this:

l = [{'A': 1, 'B': 'hello'}, 
     {'A': 2, 'B': 'hello'},
     {'A': 3, 'B': 'hello'}]

I tried with the following function:

    def unpack_dict(dict_to_unpack):
        unpacked_dicts = []
        for key in dict_to_unpack:
            if type(dict_to_unpack[key]) is list:
                for value in dict_to_unpack[key]:
                    temp_dict = dict_to_unpack
                    temp_dict[key] = value
                    unpacked_dicts.append(temp_dict)
        return unpacked_dicts if unpacked_dicts else dict_to_unpack

But I get this as a result instead:

[{'A': 3, 'B': 'hello'}, 
 {'A': 3, 'B': 'hello'}, 
 {'A': 3, 'B': 'hello'}]

Thanks for the answers.

Khronos
  • 3
  • 2
  • 3
    `temp_dict = dict_to_unpack.copy()` you need to copy your dictionary and work on it, instead of making a reference – Devesh Kumar Singh Jun 13 '19 at 09:42
  • Please clarify your use-case. Do you *always* have one concrete value and the other as a list? Can you have multiple values of different length? What is your criteria for unpacking - does it have to be a list, an iterable, or something else? – MisterMiyagi Jun 13 '19 at 09:48
  • 1
    `d1 = [{'A': entry,'B':'hello'} for entry in d['A']]` where d is ` {'A': [1, 2, 3], 'B': 'hello'}` – balderman Jun 13 '19 at 09:51
  • @MisterMiyagi The dictionary can have more than two values, but at most one is a list of any length. The result should be a list of dictionaries (I realized that my function should return a list also if the input dictionary contains no lists). – Khronos Jun 13 '19 at 10:04

1 Answers1

1

Because you are not copying a dictionary, but using the old dict: temp_dict = dict_to_unpack

You can do what you want with this code:

from copy import copy

d = {'A': [1, 2, 3], 'B': 'hello'}
result = []
for i in d['A']:
    dct = copy(d)
    dct['A'] = i
    result.append(dct)
print(result)

[{'A': 1, 'B': 'hello'}, {'A': 2, 'B': 'hello'}, {'A': 3, 'B': 'hello'}]

vurmux
  • 9,420
  • 3
  • 25
  • 45