Home > database >  convet list of values in dictionary to key pair value
convet list of values in dictionary to key pair value

Time:07-31

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'}]

CodePudding user response:

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'}]
            

CodePudding user response:

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()})

CodePudding user response:

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 :)

CodePudding user response:

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'}]
  • Related