简体   繁体   中英

convert list of values in dictionary to key pair value

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM