Skip to content

Instantly share code, notes, and snippets.

@bjjvvv
Last active September 27, 2016 07:26
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 bjjvvv/e2db0d7c4e77776e5c0eddb4fc01b73b to your computer and use it in GitHub Desktop.
Save bjjvvv/e2db0d7c4e77776e5c0eddb4fc01b73b to your computer and use it in GitHub Desktop.
from collections import defaultdict
INPUT = [{'id':1, 'abc':'2'}, {'id':1, 'abc':'3'}, {'id':2, 'abc':'2'}]
simplified_inpput = [{item['id']: item['abc']} for item in INPUT] # [{1: '2'}, {1: '3'}, {2: '2'}]
d = defaultdict(list) # 用数组初始化 dict 的 value
for item in simplified_inpput:
for key, value in item.items(): # 只循环一次
d[key].append(value)
# d = {1: ['2', '3'], 2: ['2']}
result = [{'id': key, 'abc': value} for key, value in d.items()]
print(result) # [{'id': 1, 'abc': ['2', '3']}, {'id': 2, 'abc': ['2']}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment