简体   繁体   English

将字典中的值列表转换为键对值

[英]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:我只是期待 output 像这样:

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: 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).它只是将字典转换为 DataFrame 并且 to_dict 将其重新排列回字典(根据记录)。

import pandas as pd

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

Output Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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