将每个具有相同名称的对象放入单个字典python

问题描述 投票:0回答:3

我有以下词典列表:

[{'id': '1'},
 {'name': 'test'},
 {'email': '[email protected]'},
 {'id': '2'},
 {'name': 'supra'},
 {'email': '[email protected]'},
 {'id': '3'},
 {'name': 'gtr'},
 {'email': '[email protected]'}]

我想要的是:

data_list = [{"id":"1", "name":"test", "email":"[email protected]"},
             {"id":"2", "name":"supra", "email":"[email protected]"},
             ...]

我尝试过的:

v = [{k: v for d in data_list for k, v in d.items()}]

但是上面的代码只更新了相同键名的最后一个对象原因。

知道如何解决这个问题吗?谢谢。

python list dictionary object tuples
3个回答
2
投票

假设

d
是一致的,您可以使用以下(hacky)解决方案按 3 组进行迭代:

ids = names = emails = iter(d)
data_list = [
    {
        'id': i['id'],
        'name': n['name'],
        'email': e['email']
    } for i, n, e in zip(ids, names, emails)
]

结果:

[{'id': '1', 'name': 'test', 'email': '[email protected]'}, {'id': '2', 'name': 'supra', 'email': '[email protected]'}, {'id': '3', 'name': 'gtr', 'email': '[email protected]'}]

更简单(由@fsimonjetz 建议)和我最喜欢的一个:

ids = names = emails = iter(d)
data_list = [i | n | e for i, n, e in zip(ids, names, emails)]

0
投票

使用带有

range
切片的简单列表+字典理解:

N = 3
out = [{k:v for d in data_list[i:i+N] for k,v in d.items()}
       for i in range(0, len(data_list), N)]

这使得它很容易推广到任何

N
.

变体(不是更快):

from collections import ChainMap

N = 3
out = [dict(ChainMap(*data_list[i:i+N])) for i in range(0, len(data_list), N)]

输出:

[{'id': '1', 'name': 'test', 'email': '[email protected]'},
 {'id': '2', 'name': 'supra', 'email': '[email protected]'},
 {'id': '3', 'name': 'gtr', 'email': '[email protected]'}]

使用的输入:

data_list = [{'id': '1'},
             {'name': 'test'},
             {'email': '[email protected]'},
             {'id': '2'},
             {'name': 'supra'},
             {'email': '[email protected]'},
             {'id': '3'},
             {'name': 'gtr'},
             {'email': '[email protected]'}]

0
投票

如果保证你的输入列表是三人一组,那么:

_list = [
    {
        "id": "1"
    },
    {
        "name": "test"
    },
    {
        "email": "[email protected]"
    },
    {
        "id": "2"
    },
    {
        "name": "supra"
    },
    {
        "email": "[email protected]"
    },
    {
        "id": "3"
    },
    {
        "name": "gtr"
    },
    {
        "email": "[email protected]"
    }
]

data_list = []

for i in range(0, len(_list), 3):
    data_list.append(_list[i] | _list[i+1] | _list[i+2])

print(data_list)

输出:

[{'id': '1', 'name': 'test', 'email': '[email protected]'}, {'id': '2', 'name': 'supra', 'email': '[email protected]'}, {'id': '3', 'name': 'gtr', 'email': '[email protected]'}]
© www.soinside.com 2019 - 2024. All rights reserved.