合并一个词典列表;具体用例

时间:2014-06-03 10:27:13

标签: python django dictionary

如何结合使用值从django查询获得的这个特定字典列表? :

alist=[{"id":4,"name":"joseph","movie":3},{"id":6,"name":"kiley","movie":8}, {"id":4,"name":"joseph","movie":9},{"id":6,"name":"kiley","movie":17}]

我希望:

anewlist=[{"id":4,"name":"joseph","movies":[3,9]},{"id":6,"name":"kiley","movies":[8,17]}

我知道如何使用iteritems,但我想要一种更通用的方式而不使用循环......

1 个答案:

答案 0 :(得分:1)

你只能使用理解

来做到这一点
result = [
    {
        'id': id,
        'name': next(x['name'] for x in d if x['id'] == id),
        'movies': [x['movie']  for x in d if x['id'] == id]
    }
    for id in set(x['id'] for x in d)]

但我非常怀疑这比简单循环更有效或可读。吻!