1

I have the following dictionary:

my_dict = {"A":0, "B":[1,2], "C":3}

I am trying to split this into a list of 2 dictionaries that encompass each possible value. For example:

#Desired result
[{"A":0, "B":1, "C":3}, {"A":0, "B":2, "C":3}]

I am able to get a list of each needed dictionary, in hopes I can then loop through the list and merge dictionaries using update(). This will overwrite the key "B"and only create a single dict.

Here is what I have done:

dict_list = []
my_dict = {"A":0, "B":[1,2], "C":3}

for k, v in my_dict.items():
    if type(v) == list:
        for i in v:
            dict1 = {k:i}
            dict_list.append(dict1)
    if type(v) != list:
        dict2 = {k:v}
        dict_list.append(dict2)

new_dict = {}
for d in dict_list:
    new_dict.update(d)

print(new_dict)

Output:

{'A':0, 'B':2, 'C':3}

This is overwriting the key 'B' and creating only one dictionary based on the last value.

timgeb
  • 76,762
  • 20
  • 123
  • 145
Eric T
  • 13
  • 2

1 Answers1

0

It's pretty easy if your dict can have only one list.

>>> my_dict = {"A":0, "B":[1,2], "C":3}
>>> k, lst = next((k, v) for k, v in my_dict.items() if isinstance(v, list))
>>> [{**my_dict, k:x} for x in lst]
[{'A': 0, 'B': 1, 'C': 3}, {'A': 0, 'B': 2, 'C': 3}]

It's a bit trickier if your dict can have multiple lists.

>>> from itertools import product
>>> 
>>> my_dict = {"A":0, "B":[1,2], "C":[3, 4]}
>>> lists_kv = ([(k, x) for x in v] for k, v in my_dict.items() if isinstance(v, list))
>>> [{**my_dict, **dict(x)} for x in product(*lists_kv)]
[{'A': 0, 'B': 1, 'C': 3},
 {'A': 0, 'B': 1, 'C': 4},
 {'A': 0, 'B': 2, 'C': 3},
 {'A': 0, 'B': 2, 'C': 4}]
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Marked this as the correct answer as it is absolutely doing what I needed it to do, so thank you. Could you explain what [{**my_dict, k:x} for x in lst] is actually doing? I am trying to step through but the **my_dict portion is throwing me off. – Eric T Dec 02 '18 at 23:22
  • 1
    Think I answered my own question. For anyone wondering see [What does **dict mean in python](https://stackoverflow.com/questions/21809112/what-does-tuple-and-dict-means-in-python) – Eric T Dec 02 '18 at 23:32
  • @EricT see also [How to merge two dictionaries in a single expression?](https://stackoverflow.com/a/26853961/3620003) – timgeb Dec 03 '18 at 07:37