Home > Back-end >  I want to return object with timestramp and count
I want to return object with timestramp and count

Time:10-09

I have list which contains multiple similar timestamps i have count their occurrences like below code :

count = collections.Counter(MyList)
return [{"result": count}]

It gives me result like this :

"2021-10-09T00:26:16": 10,
"2021-10-08T15:08:37": 5,
"2021-10-08T13:40:50": 6,

But I want a result like this

{"timestamp": "2021-01-01T00:00:00", "count": 10},
{"timestamp": "2021-01-02T00:00:00", "count": 5},
{"timestamp": "2021-01-03T00:00:00", "count": 6},

CodePudding user response:

You can use Dictionary Comprehension to meet the requirement.

count = collections.Counter(MyList)
result = [{'timestamp': k, 'count': v}  for k,v in count.items()]

Learn more about Dictionary Comprehension from PEP 274 -- Dict Comprehensions.

  • Related