skip to Main Content

I’m doing a course and I’m a little complicated with this exercise

I have 2 json that I have to join in a dictionary, but this must meet certain rules.

department = [
 {"ID": 1, "Name": "John", "Role": "Manager", "employees" :[
 {"ID": 4, "Name": "Mike", "Role": "Engineer"}]},
 {"ID": 3, "Name": "Sam", "Role": "Manager", "employees" :[]
 }]
employee = { "ID": [2],"Name": "Jack", "Role": "Analyst"}

1- The employee of Identifier 2 is under the charge of the Manager with Identifier 3.

2- The Database where the information will be ingested does not support columns of different data types.
To do this, a function must be generated that corrects this in the inputs.

3- The expected output must be a nested dictionary

How can I manage to join these fulfilling all conditions?

And the expected result should be this:

enter image description here

4

Answers


  1. You can update your json directly as:

    department[1]['employees'].append(employee)
    department
    
    #output
        [{'ID': 1,
      'Name': 'John',
      'Role': 'Manager',
      'employees': [{'ID': 4, 'Name': 'Mike', 'Role': 'Engineer'}]},
     {'ID': 3,
      'Name': 'Sam',
      'Role': 'Manager',
      'employees': [{'ID': [2], 'Name': 'Jack', 'Role': 'Analyst'}]}]
    
    Login or Signup to reply.
  2. I believe the best way to do it is:

    department[1]['employees'].append(employee)
    
    Login or Signup to reply.
  3. Because other employee IDs are integers (not lists), you need to extract the first item from the "ID" key to fix the input data.

    You can use the next function (or a loop) to find department 3’s dictionary in the list (hard coding the position in the list seemed like cheating to me)

    Then append the whole employee dictionary to the "employees" list in department 3

    employee["ID"] = employee["ID"][0]                        # fix employee ID
    department3 = next(d for d in department if d["ID"] == 3) # find department 3
    department3["employees"].append(employee)                 # add employee
    

    result:

    import json
    print(json.dumps(department,indent=2))
    
    [
      {
        "ID": 1,
        "Name": "John",
        "Role": "Manager",
        "employees": [
          {
            "ID": 4,
            "Name": "Mike",
            "Role": "Engineer"
          }
        ]
      },
      {
        "ID": 3,
        "Name": "Sam",
        "Role": "Manager",
        "employees": [
          {
            "ID": 2,
            "Name": "Jack",
            "Role": "Analyst"
          }
        ]
      }
    ]
    
    Login or Signup to reply.
  4. 2- The Database where the information will be ingested does not support columns of different data types. To do this, a function must be generated that corrects this in the inputs.

    You could use a function like this to enforce datatypes:

    def format_empData(val, key, enforce=False, defaultVal=None):
        if key == 'ID':
            try: return int(val[0] if val and isinstance(val, list) else val)
            except: return defaultVal if enforce else val
        return str(val)
    

    1- The employee of Identifier 2 is under the charge of the Manager with Identifier 3.

    You can loop through the departments until you find the right one and then add employee after processing each value in it with format_empData:

    managerId = 3
    for di, dept in enumerate(department):
        if dept['ID'] == managerId:
            department[di]['employees'].append(
                {k: format_empData(v, k) for k, v in employee.items()})
            break
    

    After that, department should look like

    [{'ID': 1, 'Name': 'John', 'Role': 'Manager',
      'employees': [{'ID': 4, 'Name': 'Mike', 'Role': 'Engineer'}]},
     {'ID': 3, 'Name': 'Sam', 'Role': 'Manager',
      'employees': [{'ID': 2, 'Name': 'Jack', 'Role': 'Analyst'}]}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search