Python - List of dictionary to list of list of dictionary
I have this kind of list of 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},
]
That I'd like to transform into this kind of list of list of dictionary
[
[
{'word': u'live', 'sequence': 1L, 'part': 1L}
{'word': u'school', 'sequence': 2L, 'part': 1L},
],
[
{'word': u'job', '开发者_StackOverflow中文版sequence': 1L, 'part': 2L},
{'word': u'house', 'sequence': 2L, 'part': 2L},
],
]
Based on the key part
and ordered on sequence
How can I do that ?
Since itertools
can be confusing, here's how you can do it:
>>> 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'}]]
This assumes that l
is already sorted by the part
key, if not, use
>>> 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"])]
sorted()
(or list.sort()
) and itertools.groupby()
.
Group the parts using a dictionary:
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()
To ordered by sequence, just used sorted with a sort key specified:
[sorted(dd[k], key=lambda x: x['sequence']) for k in dd]
Overall, this produces:
[[{'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'}]]
精彩评论