PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

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

 May 13, 2022     append, json, list, loops, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

1,213,701

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing