Home > Back-end >  How to concatanate 2 dictionaries in 2 json files
How to concatanate 2 dictionaries in 2 json files

Time:08-27

Iam trying to append a dictionary in one json file to a dictionary in another json file. here are json file r1

[
  {
    "Address": "Mumbai",
    "Email_ID": "[email protected]",
    "EmpCode": 1,
    "EmpName": "sumit",
    "Id": 1,
    "Phone_No": "7543668309"
  }
]

json file r2

[
  {
    "Basic": 20000.0,
    "DA": 30000.0,
    "EmpCode": 1,
    "Gross": 50000.0,
    "S_ID": 1
  }
]

The result Iam looking for is Expected result

   [
      {
        "Address": "Mumbai",
        "Email_ID": "[email protected]",
        "EmpCode": 1,
        "EmpName": "sumit",
        "Id": 1,
        "Phone_No": "7543668309"
        "Basic": 20000.0,
        "DA": 30000.0,
        "EmpCode": 1,
        "Gross": 50000.0,
        "S_ID": 1
      }
    ]

My code is not returning the expected results

def get_name(nid):
    response1 = requests.get('http://10.162.14.137:5000/users/' nid)
    response2 = requests.request(method="GET", url='http://10.162.14.137:5001/salarylist/' nid)
    #return render_template('append.html', response1=response1,response2=response2)
    r1=(response1.json())
    r2=(response2.json())
    r3=r1 r2
        
    #return render_template('append.html', r3=r3)
    return(r3)

CodePudding user response:

Your r1 and r2 are NOT dicts. They are lists having single element of dict.

Not sure what you are trying to achieve but

# Python 3.9 
r3 = [ r1[0] | r2[0] ]

# Prior to 3.9
r3 = [ { **(r1[0]), **(r2[0]) } ]

should work

CodePudding user response:

As the 'Adrian shum' said your json having the lists. in that case you can use nested for loops.

result = []
for i, j in zip(r1, r2):
     result.append(i | j)
print(result)
>>> [{'Address': 'Mumbai', 'Email_ID': '[email protected]', 'EmpCode': 1, 'EmpName': 'sumit', 'Id': 1, 'Phone_No': '7543668309', 'Basic': 20000.0, 'DA': 30000.0, 'Gross': 50000.0, 'S_ID': 1}]
  • Related