【问题标题】:How to Append a List Key Value using Another List如何使用另一个列表附加列表键值
【发布时间】:2021-09-18 05:08:45
【问题描述】:

我一直在努力让它发挥作用。 有两个不同的 JSON 列表包含不同的键。

列表1

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

列表2

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

代码

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

我得到的输出是,

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

预期输出

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

循环遍历键,如果 key['name'] 在两个列表中相等, 然后它继续发生来自给定键的特定值。 唯一的问题是它对我来说不能正常工作。我只想用测量中的值替换特征中的高度值。

[编辑]: 我对json进行了更改。现在应该是正确的。基本上,height 是一个数组。

【问题讨论】:

  • [key['name']] 缺少]
  • 您提交的代码有语法错误。 @Sujay 指出的一个问题,例如在list2 中,“高度”中缺少一个结束引号,并且在其值(6.0 和 5.11)之后有一个额外的冒号。更重要的是,如果这些项目应该是key: value 格式,那么它们应该是字典,而不是列表。
  • 我修好了。那是我的错误,因为我键入它而不是复制和粘贴它。至于钥匙,我该如何解决?我将这个精确的 for 循环与另一个脚本中的 if 语句一起使用。虽然,那个 for 循环是用于查找键是否为 not in 另一个列表。
  • 您可以使用字典,如"characteristics": {"height": "5.10", "age", 25},但我个人认为在主字典中只使用heightage 以及name 并没有什么意义。跨度>
  • 我尝试将 if 语句切换为 list1.get('name') == list2.get('name')

标签: python json list loops append


【解决方案1】:

您发布的 JSON 无效,因此我对其进行了一些修复。以下代码应该可以工作:

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)

这给了我们以下结果:

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

【讨论】:

  • 当我使用你写下的循环时,它会抛出错误:“TypeError: string indices must be integers”
  • 我猜你有不同的输入?只需复制并粘贴我提供的内容。它有效
  • 实际上,list_1 对我来说我已经将它附加到一个列表 list1 = [] 并且 list2 也是如此。我在收到响应后这样做了,然后循环遍历它,以便将其添加为列表。我不知道这与您的代码相比是否有所不同。
  • 所以,现在我明白了字典和列表之间的区别。我以为我正在处理一个列表。上面的json实际上是一个dict。那么,如何修改我的 if 语句以使其与 dict 一起使用?
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多