Home > Software design >  convert list of dictionary values in to list of values
convert list of dictionary values in to list of values

Time:08-05

Hi all below is my list of dictionary

a=[{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'}, {'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]

iam expecting output like this

a={"Name":["dhaya","rishi],"Place":["pune","maharastra"],Designation:["fleetEngineer","Sr.Manager"] "}

can any one assist

CodePudding user response:

One can use nested for loops for this:

inputList = [{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'}, {
    'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]

outputDict = {}
for origDict in inputList:
    for key, val in origDict.items():
        if key in outputDict:
            outputDict[key].append(val)
        else:
            outputDict[key] = [val]

print(outputDict)

CodePudding user response:

a=[{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'}, {'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]

Name = []
Place = []
Designation = []

for ele in a:
    Name.append(ele["Name"])
    Place.append(ele["Place"])
    Designation.append(ele["Designation"])

new_a = {}

new_a['Name'] = Name
new_a['Place'] = Place
new_a["pune"] = Designation
print(new_a)

CodePudding user response:

new_dict is the answer to the question you posted. Its the smallest and simplest.

b = list(a[0].keys())
new_dict = {}
for x in b:
    new_dict[x]  = [l[x] for l in a]
print('My expected dictionary',new_dict)
  • Related