Home > Blockchain >  Python help needed to create a nested data dictionary
Python help needed to create a nested data dictionary

Time:05-04

I have the data as below

    `{"employeealias":"101613177","firstname":"Lion","lastname":"King","date":"2022-04-21","type":"Thoughtful Intake","subject":"Email: From You Success Coach"}`

    `{"employeealias":"101613177","firstname":"Lion","lastname":"King","date":"2022-04-21","type":null,"subject":"Call- CDL options & career assessment"}`

I need to create a dictionary like the below. Please help. enter image description here

CodePudding user response:

You can create a nested dictionary inside Python like this: student = {name : "Suman", Age = 20, gender: "male",{class : 11, roll no: 12}}

CodePudding user response:

You have to create new dictionary with list and use for-loop to check if exists employeealias, firstname, lastname to add other information to sublist. If item doesn't exist then you have to create new item with employeealias, firstname, lastname and other information.

data = [
{"employeealias":"101613177","firstname":"Lion","lastname":"King","date":"2022-04-21","type":"Thoughtful Intake","subject":"Email: From You Success Coach"},
{"employeealias":"101613177","firstname":"Lion","lastname":"King","date":"2022-04-21","type":"null","subject":"Call- CDL options & career assessment"},
]

result = {'interactions': []}

for row in data:
    found = False
    for item in result['interactions']:
        if (row["employeealias"] == item["employeealias"]
           and row["firstname"] == item["firstname"]
           and row["lastname"] == item["lastname"]):
            item["activity"].append({
               "date": row["date"],
               "subject": row["subject"],
               "type": row["type"],
            })
            found = True
            break
        
    if not found:
        result['interactions'].append({
            "employeealias": row["employeealias"],
            "firstname": row["firstname"],
            "lastname": row["lastname"],
            "activity": [{
                           "date": row["date"],
                           "subject": row["subject"],
                           "type": row["type"],
                        }]
        })
            
print(result)            
  • Related