Last active
September 27, 2016 07:26
-
-
Save bjjvvv/e2db0d7c4e77776e5c0eddb4fc01b73b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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