Home > OS >  Making a nested dictionaries from a list of dictionaries
Making a nested dictionaries from a list of dictionaries

Time:10-05

PROBLEM STATEMENT

x is an input list of dictionaries which needs to be formatted to y which is also a list of dictionaries , but in this case the key is pickupAddress and the sub dictionary consist of { zipcode,lat,long}

so basically , i want to transform x to y

Approach taken

  1. have used tuples to store the values and then inserted to a list

code screenshot

deliveryAddress={}
pickupAddress={}
l1=[]
l2=[]
l1_del=[]
l2_pick=[]
for i in range(len(x)):
    k1=('zipcode',x[i]['delivery_zip'])
    l1.append(k1)
    k2=('longitude',x[i]['delivery_lng'])
    l1.append(k2)
    k3=('latitude',x[i]['delivery_lat'])
    l1.append(k3)
    
    k4=('zipcode',x[i]['latitude'])
    l2.append(k4)
    k5=('longitude',x[i]['longitude'])
    l2.append(k5)
    k6=('latitude',x[i]['zipcode'])
    l2.append(k6)
    
    t1=("pickupAddress",l1)
    t2=("deliveryAddress",l2)
    
    print(l1)
    print(l2)
    if i < len(x):
        print(len(x))
        l1_del.append(t1)
        l2_pick.append(t2)
        del l1
        del l2 
        
        l1=[]
        l2=[]

INPUT

LIST_OF_DICTIONARY INPUT

CODE SNIPET

[{'delivery_zip': '12432',
  'delivery_lat': 42.0437,
  'delivery_lng': -73.9474,
  'distance': 43.81927669168279,
  'latitude': 41.6770047,
  'longitude': -73.7535413,
  'zipcode': 12510},
 {'delivery_zip': '12404',
  'delivery_lat': 41.8293989,
  'delivery_lng': -74.2414092,
  'distance': 43.872670571109516,
  'latitude': 41.6770047,
  'longitude': -73.7535413,
  'zipcode': 12510}]

OUTPUT

OUTPUT_FORMAT

y=[{
    "pickupAddress": { "zipcode": "12510", "latitude": 41.6770047, "longitude": -73.7535413 }, 
    "deliveryAddress": { "zipcode": "12432", "latitude": 42.0437, "longitude": -73.9474 }
  },
    {
     "pickupAddress": { "zipcode": "12510", "latitude": 41.6770047, "longitude": -73.7535413 },  
    "deliveryAddress": { "zipcode": "12404", "latitude": 41.8293989, "longitude": -74.2414092 }
  }

]

output approach1

CodePudding user response:

To transform one list into another list, use a list comprehension:

y = [
        {
            "pickupAddress": { "zipcode": obj['zipcode'], "latitude": obj['latitude'], "longitude": obj['longitude']},
            "deliveryAddress": {"zipcode": obj['delivery_zip'], "latitude": obj['delivery_lat'], "longitude": obj['delivery_lng'] }
        }
        for obj in x
    ]
  • Related