Python - 字典列表的字典列表

时间:2011-09-23 10:19:48

标签: python list dictionary

我有这种字典列表

[
  {'word': u'live', 'sequence': 1L, 'part': 1L},
  {'word': u'school', 'sequence': 2L, 'part': 1L},
  {'word': u'job', 'sequence': 1L, 'part': 2L},
  {'word': u'house', 'sequence': 2L, 'part': 2L},
]

我想转换成这种字典列表

[
  [
    {'word': u'live', 'sequence': 1L, 'part': 1L}
    {'word': u'school', 'sequence': 2L, 'part': 1L},
  ],
  [
    {'word': u'job', 'sequence': 1L, 'part': 2L},
    {'word': u'house', 'sequence': 2L, 'part': 2L},
  ],
]

基于密钥part并在sequence

上排序

我该怎么做?

3 个答案:

答案 0 :(得分:3)

由于itertools可能令人困惑,因此您可以采取以下措施:

>>> import pprint
>>> import itertools
>>> l = [
...   {'word': u'live', 'sequence': 1L, 'part': 1L},
...   {'word': u'school', 'sequence': 2L, 'part': 1L},
...   {'word': u'job', 'sequence': 1L, 'part': 2L},
...   {'word': u'house', 'sequence': 2L, 'part': 2L},
... ]

>>> l2 = [sorted(list(g), key=lambda x:x["sequence"])
...       for k, g in itertools.groupby(l, key=lambda x:x["part"])]

>>> pprint.pprint(l2)
[[{'part': 1L, 'sequence': 1L, 'word': u'live'},
  {'part': 1L, 'sequence': 2L, 'word': u'school'}],
 [{'part': 2L, 'sequence': 1L, 'word': u'job'},
  {'part': 2L, 'sequence': 2L, 'word': u'house'}]]

这假定l已经按part键排序,如果没有,请使用

>>> l2 = [sorted(list(g), key=lambda x:x["sequence"])
...       for k, g in itertools.groupby(sorted(l, key=lambda x:x["part"]), 
...                                     key=lambda x:x["part"])]

答案 1 :(得分:1)

sorted()(或list.sort())和itertools.groupby()

答案 2 :(得分:1)

使用字典对部件进行分组:

import collections

dictlist = [
  {'word': u'live', 'sequence': 1L, 'part': 1L},
  {'word': u'school', 'sequence': 2L, 'part': 1L},
  {'word': u'job', 'sequence': 1L, 'part': 2L},
  {'word': u'house', 'sequence': 2L, 'part': 2L},
]

dd = collections.defaultdict(list)
for d in dictlist:
    dd[d['part']].append(d)
dd.values()

按顺序排序,只使用已指定的排序键排序:

[sorted(dd[k], key=lambda x: x['sequence']) for k in dd]

总的来说,这会产生:

[[{'part': 1L, 'sequence': 1L, 'word': u'live'},
  {'part': 1L, 'sequence': 2L, 'word': u'school'}],
 [{'part': 2L, 'sequence': 1L, 'word': u'job'},
  {'part': 2L, 'sequence': 2L, 'word': u'house'}]]