Venkat Venkat Venkat Venkat - 7 days ago 5
Python Question

collect dictionairy values in python list

I have a list which has dict values in it. I want to group by ts and collect other values. Please note that ts is common and will be there in all dictionaries in the list. But the other values like HP, BP can change in each dictionary.
Please suggest.

input

[
{'ts': '2016-11-29 19:01', u'HP': 1},
{'ts': '2016-11-29 19:01', u'BP': 1},
{'ts': '2016-11-29 19:01', u'AP': 1},
{'ts': '2016-11-29 19:02', u'HP': 1},
{'ts': '2016-11-29 19:02', u'AP': 1}
]


output

[
{'ts': '2016-11-29 19:01', u'HP': 1, u'BP': 1,u'AP': 1 },
{'ts': '2016-11-29 19:02', u'HP': 1, u'AP': 1}
]

Answer

You can use itertools.groupby()

from itertools import groupby

result = []
for _, v in groupby(a,lambda x:x['ts']):
    temp_dict = {}
    for dic in v:
        temp_dict.update(dic)
    result.append(temp_dict)

print result

Output:

[
 {u'AP': 1, u'HP': 1, u'BP': 1, 'ts': '2016-11-29 19:01'}, 
 {u'AP': 1, u'HP': 1, 'ts': '2016-11-29 19:02'}
]