Home > Enterprise >  Converting the dictionary inside the list to the nested dictionary
Converting the dictionary inside the list to the nested dictionary

Time:03-24

have a list of tuples, called employee_data, where each list element is a tuple that corresponds to a class and a point that a employee can earn. For example,

employee_data = 
[{
   "name": "asd",
   "lastname": "abc",
   "birthday": 15/15/2021,
   "birthplace": "CA",
   "live_place": "USA",
   "email": "sss.com",
   "website": "sss.com",
   "Phone_number": "12345678901",
   "work_number": "abc",
   "save_date": 15/15/2021,
   "start_date": 15/15/2021,
   "leave_date": 15/15/2021,
   "project": "End-Of-Support",
   "age_in_months": 256 ,
   "Age_in_Years": 15.3,
   "Computer_name": 'pc1',
   "computer_cpu": 8,
   "computer_ram": 12,
   "computer_ssd": 256,
 },
 {
   "name": "asd",
   "lastname": "abc",
   "birthday": 16/15/2021,
   "birthplace": "CA",
   "live_place": "USA",
   "email": "sss.com",
   "website": "sss.com",
   "Phone_number": "12345678901",
   "work_number": "abc",
   "save_date": 15/15/2021,
   "start_date": 15/15/2021,
   "leave_date": 15/15/2021,
   "project": "End-Of-Support",
   "age_in_months": 256 ,
   "Age_in_Years": 15.3,
   "Computer_name": 'pc1',
   "computer_cpu": 8,
   "computer_ram": 12,
   "computer_ssd": 256,
 }]
Nested Dict ID name lastname birthday birthplace live_place email
0 asd abc 15/15/2021 USA CAD [email protected]
1 asd2 abc 16/15/2021 CAD USA [email protected]

I tried this functions but couldn't fix error. Here's a link!

My issue is, this dictionary in list. I want to create nested dict for mapping datas.

[{0{"name": "asd",
   "lastname": "abc",
   "birthday": 15/15/2021,
   "birthplace": "CA",
   "live_place": "USA",
   "email": "sss.com",}
1{"name": "asd2",
   "lastname": "abc",
   "birthday": 16/15/2021,
   "birthplace": "CA",
   "live_place": "USA",
   "email": "sss.com",}]

if employee has same last name i want to get employee nestedDictID than i'll import all infomartion on different list and table ..

d = { x['lastname']: x['abc'] for x in employee_data}
KeyError: 'abc'

CodePudding user response:

You can create a list of tuples with the required data extracted from json which you can use to export it to SQL tables. Refer the below code:

import pandas as pd
data = [(item.get('name'), item.get('lastname'),item.get('birthday'),item.get('birthplace'), item.get('live_place'), item.get('email')) for item in employee_data]
print(data)

df = pd.DataFrame.from_records(data, columns=['name', 'lastname', 'birthday','birthplace','live_place','email']))

And then you can use df.to_sql from pandas.

  • Related