covert dictionary to a list of dictionary

Question:

dct = {
    "a": ["apple", "orange"],
    "b": ["beijing", "shanghai"],
    "c": ["china"],
}

dct is a dictionary, value in it is a list ie:

dct={'x':["xx,"yy"],'y':<another list>,....}

to

new_list_dct=[
    {'a':'apple','b':'beijing','c':'china'},
    {'a':'apple','b':'shanghai','c':'china'},
    {'a':'orange','b':'beijing','c':'china'},
    {'a':'orange','b':'shanghai','c':'china'},
]

I want split all values in dct, and make a new list of dct, and dct in list is the same key as dct, but value are from dct’s list like above

I spent two hours to failed to covert from dct to new_list_dct, but failed, anyone can help? dct could be any dictionary (maybe use different key) but the same structure

what I tried is

new_list_dct=[]
for i in dct['a']:
    for j in dct['b']:
        for k in dct['c']:
            data={'a':i,'b':j,'c':k}
            new_list_dct.append(data)
pprint(new_list_dct)

But this method is not general, since the key could not ‘a’,’b’,’c’ for a given dct.

Asked By: user1334609

||

Answers:

You can do it recursively like this

from copy import deepcopy
dct = {
    "a": ["apple", "orange"],
    "b": ["beijing", "shanghai"],
    "c": ["china"],
}

def recursive(items, index, cur, results):
    if index >= len(items):
        results.append(cur)
        return
    
    temp = items[index]
    for i in range(0, len(temp)):
        cur.append(temp[i])
        z = deepcopy(cur)
        recursive(items, index+1, z, results)
        cur.pop()


items = [
    [{key: value} for value in list_items]
    for key, list_items in dct.items()
]

results, cur = [], []
recursive(items, 0, cur, results)

result_dicts = []
for item in results:
    f_dict = {}
    for each in item:
        f_dict.update(each)
    
    result_dicts.append(f_dict)

print(result_dicts)
Answered By: Vikrant Srivastava
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.