0

I am trying to split a dictionary of lists into a list of dictionaries.

I have tried following the examples here and here_2. Here_2 is for python 2.x and does not seem to work on python 3.x

The first linked example, here, almost works except I only get the first dictionary key value pair back as 1 list.

using zip() to convert dictionary of list to list of dictionaries

test_dict = { "Rash" : [1], "Manjeet" : [1], "Akash" : [3, 4] } 
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())] 
print ("The converted list of dictionaries " +  str(res)) 

Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}] 

DESIRED Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}, {‘Akash’: 4}]
krkaufma
  • 39
  • 7
  • What have you tried other than those examples? Understandably you're probably not going to find something that addresses your specific use case. Also, it looks like you're trying to group them by index, so for the second index you'd need a second dictionary – IanQ Dec 16 '19 at 21:11
  • The above example is the closest I have gotten to the desired answer. Yes, I am trying to group the values by their keys. The keys also do not have an equal number of values. – krkaufma Dec 16 '19 at 21:16
  • 1
    Running your example I get output `The converted list of dictionaries [{'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}]` – Andrej Kesely Dec 16 '19 at 21:26
  • I have edited test_dict and the outputs to clarify my issue. – krkaufma Dec 16 '19 at 21:57

2 Answers2

1

Here's a slow and brittle solution with no bells or whistles (and bad naming in general):

def dictlist_to_listdict(dictlist):
    output = []
    for k, v in dictlist.items():
        for i, sv in enumerate(v):
            if i >= len(output):
                output.append({k: sv})
            else:
                output[i].update({k: sv})
    return output


if __name__ == "__main__":
    test_dict = {"Rash": [1], "Manjeet": [1], "Akash": [3, 4]} 
    print(dictlist_to_listdict(test_dict))
R001W
  • 71
  • 3
0

When I ran your code on my notebook with Python 3, it does print the line you put as the desired output. Perharps I don't understand the question well enough

Mayowa Ayodele
  • 549
  • 2
  • 11