Skip to content

Instantly share code, notes, and snippets.

@shiyanhui
Created September 23, 2016 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiyanhui/a9c4ac8de02cf93658b72da0b89badd4 to your computer and use it in GitHub Desktop.
Save shiyanhui/a9c4ac8de02cf93658b72da0b89badd4 to your computer and use it in GitHub Desktop.
groupby
import itertools
t1 = [{"id": 1, "abc": "2"}, {"id": 1, "abc": "3"}, {"id": 2, "abc": "2"}]
print [{"id": k, "abc": (lambda v: [item["abc"] for item in v] if len(v) > 1 else v[0]["abc"])(list(group))} for k, group in itertools.groupby(t1, lambda item: item["id"])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment