如何将具有相同ID的对象放到对象列表中

时间:2019-04-17 17:26:18

标签: python python-3.x list

我有一个对象:

object = [
    [{
        id: 1,
        name: "a",
        age: 20
    },
    {
        id: 2,
        name: "b",
        age: 19
    }],
    [{
        id: 1,
        address: "something",
        email: "something@"
    },
    {
        id: 2,
        address: "helpppp",
        email: "something"
    }]
];

我想要这个:

object = [
    {
        id: 1,
        name: "a",
        age: 20
        address: "something",
        email: "something@"
    },
    {
        id: 2,
        name: "a",
        age: 19
        address: "helpppp",
        email: "something"
    }
];

2 个答案:

答案 0 :(得分:1)

我不确定您为什么使用列表列表,您可以将每个字典轻松地存储在列表中,但是如果您对此无法控制,我会提出以下建议:

  1. 字典中的键需要用单引号或双引号引起来。
  2. 您可以使用以下代码找到id个字典: ids = set(sum([[y['id'] for y in x] for x in object], []))

此语句有点费解,因为它使用列表理解sum(从列表列表中获取单个元素,而set则获得唯一的id。)以下应该适用于您描述的示例:

flat_object = sum(object, [])
ids = set(sum([[y['id'] for y in x] for x  in object], []))

merged_object = list()
for obj_id in ids:
    same = [x for x in flat_object if x['id'] == obj_id]
    merged = same[0]
    for x in same[1:]:
        merged.update(x)
    merged_object.append(merged)
print(merged_object)
# output
# [{'id': 1, 'name': 'a', 'age': 20, 'address': 'something', 'email': 'something@'}, 
{'id': 2, 'name': 'b', 'age': 19, 'address': 'helpppp', 'email': 'something'}]

答案 1 :(得分:1)

假设您可以以JSON / python dict格式而不是Javascript对象的形式导出对象,则将可以执行以下操作。 pprint用于格式化输出格式。

from collections import defaultdict
from pprint import pprint


def combine_list_of_list_of_dicts(source):
    output = defaultdict(dict)
    for a in source:
        for b in a:
            output[b["id"]].update(b)

    return list(output.values())


source = [
    [
        {
            "id": 1,
            "name": "a",
            "age": 20
        },
        {
            "id": 2,
            "name": "b",
            "age": 19
        }
    ],
    [
        {
            "id": 1,
            "address": "something",
            "email": "something@"
        },
        {
            "id": 2,
            "address": "helpppp",
            "email": "something"
        }
    ]
]


result = combine_list_of_list_of_dicts(source)
pprint(result)

给予

[{'address': 'something',
  'age': 20,
  'email': 'something@',
  'id': 1,
  'name': 'a'},
 {'address': 'helpppp', 'age': 19, 'email': 'something', 'id': 2, 'name': 'b'}]