convert list of values in dictionary to key pair value

Question:

Hi iam having below dictionary with values as list

a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}

iam just expecting output like this:

a=[{"Name":"ANAND",'Place':'Chennai','Designation':'Developer'},{"Name":"kumar",'Place':'Banglore','Designation':'Sr.Developer'}]
Asked By: anand

||

Answers:

this should do the trick :

a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}

ans = []
num_of_dicts = len(list(a.values())[0])
for i in range(num_of_dicts):
    ans.append({key:val[i] for key,val in a.items() })

print(ans)

output:

[{'Name': 'ANAND', 'Place': 'Chennai', 'Designation': 'Developer'}, {'Name': 'kumar', 'Place': 'Banglore', 'Designation': 'Sr.Developer'}]

if you have any questions feel free to ask me in the commennts 🙂

Answered By: Ohad Sharet

You can try in this way:

a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
out = []
keys = list(a.keys())
for i in range(len(a[keys[0]])):
    temp = {}
    for j in keys:
        temp[j] = a[j][i]
    out.append(temp)
print(out)
#Output - [{'Name': 'ANAND', 'Place': 'Chennai', 'Designation': 'Developer'}, {'Name': 'kumar', 'Place': 'Banglore', 'Designation': 'Sr.Developer'}]
            
Answered By: SAI SANTOSH CHIRAG

Use list comprehension

newlist = []
newlist.append({key: value[0] for key, value in a.items()})
newlist.append({key: value[1] for key, value in a.items()})

If the length is long:

newlist = []
for i in range(len(a[list(a.keys())[0]])):
    newlist.append({key: value[i] for key, value in a.items()})
Answered By: Geeky Quentin

Try this. It just converts to dictionary into a DataFrame and to_dict rearranges it back into a dictionary (according to records).

import pandas as pd

a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
pd.DataFrame(a).to_dict('records')

Output

[{'Designation': 'Developer', 'Name': 'ANAND', 'Place': 'Chennai'},
 {'Designation': 'Sr.Developer', 'Name': 'kumar', 'Place': 'Banglore'}]
Answered By: DrCorgi
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.