Home > Blockchain >  Python combine JSON data variables
Python combine JSON data variables

Time:03-26

I've been researching this issue for a while and haven't been able to find a working solution, so I'm hoping someone here can show me what I'm missing. I'm creating JSON structured variables from separate API calls and looking to combine the results. Here's what I have:

my_list1 = jmespath.search("output[*]{'name1': value1[*].name, 'name2': value2[*].name, 'name3': value3[*].name}[]", response1)

my_list2 = jmespath.search("output[*]{'name4': value4[*].name, 'name5': value5[*].name, 'name6': value5[*].name}[]", response2)

The output from these variables looks like:

my_list1:
      {
        "name1": [
          "somevalue1",
          "somevalue2",
          "somevalue3"
        ],
        "name2": [
          "somevalue4"
        ],
        "name3": [
          "somevalue5"
        ]
      }
my_list2:
      {
        "name4": [
          "othervalue1",
          "othervalue2",
          "othervalue3"
        ],
        "name5": [
          "othervalue4"
        ],
        "name6": [
          "othervalue5"
        ]
      }

I'm trying to combine these two into one statement, but the closest I seem to able to get is with the following:

my_list1.extend(my_list2)

This results in:

      {
        "name1": [
          "somevalue1",
          "somevalue2",
          "somevalue3"
        ],
        "name2": [
          "somevalue4"
        ],
        "name3": [
          "somevalue5"
        ]
      },
      {
        "name4": [
          "othervalue1",
          "othervalue2",
          "othervalue3"
        ],
        "name5": [
          "othervalue4"
        ],
        "name6": [
          "othervalue5"
        ]
      }

What I need is:

      {
        "name1": [
          "somevalue1",
          "somevalue2",
          "somevalue3"
        ],
        "name2": [
          "somevalue4"
        ],
        "name3": [
          "somevalue5"
        ],
        "name4": [
          "othervalue1",
          "othervalue2",
          "othervalue3"
        ],
        "name5": [
          "othervalue4"
        ],
        "name6": [
          "othervalue5"
        ]
      }

I've also tried 'append' and 'insert' as well with no luck. I assume I'm missing something simplistic. Please help!

CodePudding user response:

What you're missing is that both your lists contain one dictionary each. It is this dictionary that you want to update, not the list that contains it. Do

my_dict1 = my_list1[0]
my_dict2 = my_list2[0]

my_dict1.update(my_dict2)

which gives:

mydict1 = {'name1': ['somevalue1', 'somevalue2', 'somevalue3'],
 'name2': ['somevalue4'],
 'name3': ['somevalue5'],
 'name4': ['othervalue1', 'othervalue2', 'othervalue3'],
 'name5': ['othervalue4'],
 'name6': ['othervalue5']}
  • Related