How to decrypt or convert Python Dictionary of lists to normal dictionary


Very new to python and literally struggling to get this fixed. I have dictionary like below from json file. I believe this is being called as Dictionary of lists.

MyDict = [{Key:[1,2,3,4]}, {Summary:[Text 1, Text 2, Text 3, Text 4]}]

Expected Result:
How to convert this to

{Key:1, Summary:Text 1}
{Key:2, Summary:Text 2}
{Key:3, Summary:Text 3}
{Key:4, Summary:Text 4}

No idea on how to achieve this..

Asked By: JamesDataAnalyst



You can iterate through the list:

   MyDict = {'Key':[1,2,3,4], 'Summary':['Text 1', 'Text 2', 'Text 3', 'Text 4']}

result = []
for i in range(len(MyDict['Key'])):
    key = MyDict['Key'][i]
    summary = MyDict['Summary'][i]
    result.append({ 'Key': key, 'Summary': summary })



[{'Key': 1, 'Summary': 'Text 1'}, {'Key': 2, 'Summary': 'Text 2'}, {'Key': 3, 'Summary': 'Text 3'}, {'Key': 4, 'Summary': 'Text 4'}]
Answered By: Abdulmajeed

I would start by extracting the lists from the data, as it would be easier to work with.

keys = MyDict[0]['Key']
values = MyDict[1]['Summary']

Then you can use zip to combine the two lists together and loop over them like so

res = []
for k, v in zip(keys, values):
    res.append({'Key': k, 'Summary': v})

Given the new data, it looks like is should actually be.

MyDict = {'Key':[1,2,3,4], 'Summary':['Text 1', 'Text 2', 'Text 3', 'Text 4']}

So the only change you would need to make is to remove the indices when extracting the list.

keys = MyDict['Key']
values = MyDict['Summary']
    {'Key': 1, 'Summary': 'Text 1'},
    {'Key': 2, 'Summary': 'Text 2'},
    {'Key': 3, 'Summary': 'Text 3'},
    {'Key': 4, 'Summary': 'Text 4'}

If you want to save it as a dictionary, not a list you can do:

res = {}
for k, v in zip(keys, values):
    res[k] = v

The output of this would be a dictionary where each key is a number and the value is the summary:

    1: 'Text 1',
    2: 'Text 2',
    3: 'Text 3',
    4: 'Text 4'

If you want to do something with them as individual dictionaries you can do an operation on them instead of storing them in another dictionary.

for k, v in zip(keys, values):
    do_something({k: v})

This would call do_something with a new dict for each key-value pair, so the first would be {1: 'Text 1'} and so on.

Answered By: Zelkins