Friday, May 13, 2022

[FIXED] How to Append a List Key Value using Another List

Issue

I've been trying to get this to work. There are two different JSON lists that contain different keys.

list1

[
    {
        "name":"John",
        "measurement": "5.11"
    },
    {
        "name":"Kate",
        "measurement": "5.6"
    }
]

list2

[
    {
        "name":"John",
        "characteristics": {
            "height": [
            "6.0"
            ]
        }
    },
    {
        "name":"Mike",
        "characteristics": {
            "height": [
            "5.10"
            ]
        }
    }
]

code

for k in list2:
    if v['name'] in [key['name'] for key in list1:
        list1.append(k['measurement'])

The output I get is,

[{'name': 'John', 'characteristics': ['height': '6.0', 'age': 30}, '5.11']

Expected output

[{'name': 'John', 'characteristics': ['height': '5.11', 'age': 30}]

The loops go over the keys and if the key['name'] are equals in both lists, then it proceeds into happening that specific values from the given key. The only problem is that it is not working correctly for me. I just want to replace that value from height in characteristics with the one in measurement.

[EDIT]: I made changes to the json. It should be correct now. Basically, height is an array.


Solution

JSON you posted is invalid so I fixed it little bit. Following code should work:

list_1 = [
    {
        "name": "John",
        "measurement": "5.11"
    },
    {
        "name": "Kate",
        "measurement": "5.6"
    }
]

list_2 = [
    {
        "name": "John",
        "characteristics": {
            "height": "6.0",
            "age": 30
        }
    },
    {
        "name": "Mike",
        "characteristics": {
            "height": "5.10",
            "age": 25
        }
    }
]



result = []
for list_1_item in list_1:
    single_obj = {}
    for list_2_item in list_2:
        if list_2_item['name'] == list_1_item['name']:
            single_obj['name'] = list_1_item['name']
            single_obj['characteristics'] = list_2_item['characteristics']
            result.append(single_obj)

print(result)

This gives us following result:

[{'name': 'John', 'characteristics': {'height': '6.0', 'age': 30}}]


Answered By - dchoruzy
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.