python - 合并具有列表 init 的字典列表

标签 python python-2.7

我当前的列表:

my_list = [
   {'id': 1, 'val': [6]},
   {'id': 2, 'val': [7]},
   {'id': 3, 'val': [8]},
   {'id': 2, 'val': [9]},
   {'id': 1, 'val': [10]},
]

期望的输出:

my_list = [
   {'id': 1, 'val': [6, 10]},
   {'id': 2, 'val': [7, 9]},
   {'id': 3, 'val': [8]},
]

到目前为止我尝试了什么:

    my_new_list = []
    id_set = set()

    for d in my_list:
        if d['id'] not in id_set:
            id_set.add(d['id'])
            temp = {'id': d['id'], 'val': d['val']}
            my_new_list.append(temp)
        else:
             # loop over the new list and find the dict which already have d['id'] and update by appending value
             # but this is not efficient

任何其他更有效的方法或者可能是我不知道的一些内置函数。

PS:顺序很重要!

最佳答案

.setdefault()是你的 friend :

(我们应该使用 collections.OrderedDict 来记住键首次插入的顺序。)

>>> import collections

>>> result = collections.OrderedDict()
>>> for d in my_list:
...     result.setdefault(d["id"], []).extend(d["val"])

>>> lst = []
>>> for k, v in result.items():
...     lst.append({"id": k, "val": v})

关于python - 合并具有列表 init 的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37109624/

相关文章:

python - Azure Active Directory 错误。访问 token 来自错误的颁发者

python - 将对象转储到 JSON 文件的两种方法有什么区别吗?

python - 滥用 'property' 保留字

python - 在 Python 中,dict.pop(a,b) 是什么意思?

python - Pandas - 根据其他列创建总计列

python manage.py runserver、shell、dbshel​​l 在 git-bash 上卡住

python - 如何将 websocket push api 输出写入文本文件?

Python:将上下文(contextvars.Context)复制到单独的线程

python - plotly Python : Multiple item selection interactive plot

python - param ['pagetoken' ] 是示例 Google 报告代码中的语法错误吗?