简体   繁体   中英

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', '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() (或list.sort() )和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'}]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM