I have this list dictionary in python
accidents_dict = [{'date': 'new Date (2017,1,1)', 'Fall': 5},
{'date': 'new Date (2017,1,1)', 'Vehicular Accident': 127},
{'date': 'new Date (2017,1,1)', 'Medical': 129},
{'date': 'new Date (2017,1,1)', 'OB': 10},
{'date': 'new Date (2017,1,1)', 'Mauling': 9},
{'date': 'new Date (2017,2,1)', 'Fall': 7},
{'date': 'new Date (2017,2,1)', 'Vehicular Accident': 113},
{'date': 'new Date (2017,2,1)', 'Mauling': 5},
{'date': 'new Date (2017,2,1)', 'OB': 9},
{'date': 'new Date (2017,2,1)', 'Medical': 79},
{'date': 'new Date (2017,3,1)', 'Medical': 112},
{'date': 'new Date (2017,3,1)', 'Mauling': 5},
{'date': 'new Date (2017,3,1)', 'OB': 11},
{'date': 'new Date (2017,3,1)', 'Vehicular Accident': 119}, {'date': 'new Date (2017,3,1)', 'Fall': 8}]
My desired output is to group them by date and to remove the single quote in the date value. This is my desired output:
accidents_dict =[{
"date": new Date(2017, 1, 1),
"Vehicular Accident": 127,
"Medical': 129,
"OB": 10,
"Mauling": 9
}, {
"date": new Date(2017, 2, 1),
"Fall": 7,
"Vehicular Accident': 113,
"Mauling": 5,
"OB": 9,
"Medical": 79
}, {
"date": new Date(2017, 3, 1),
"Medical": 112,
"Mauling": 5,
"OB": 11,
"Vehicular Accident": 119,
"Fall": 8
}]
I tried this:
from itertools import groupby
from operator import itemgetter
for key, value in groupby(accidents_dict, key = itemgetter('date')):
print(key)
for k in value:
print(k)
This was the result:
new Date (2017,1,1)
{'date': 'new Date (2017,1,1)', 'Fall': 5}
{'date': 'new Date (2017,1,1)', 'Vehicular Accident': 127}
{'date': 'new Date (2017,1,1)', 'Medical': 129}
{'date': 'new Date (2017,1,1)', 'OB': 10}
{'date': 'new Date (2017,1,1)', 'Mauling': 9}
new Date (2017,2,1)
{'date': 'new Date (2017,2,1)', 'Fall': 7}
{'date': 'new Date (2017,2,1)', 'Vehicular Accident': 113}
{'date': 'new Date (2017,2,1)', 'Mauling': 5}
{'date': 'new Date (2017,2,1)', 'OB': 9}
{'date': 'new Date (2017,2,1)', 'Medical': 79}
new Date (2017,3,1)
{'date': 'new Date (2017,3,1)', 'Medical': 112}
{'date': 'new Date (2017,3,1)', 'Mauling': 5}
{'date': 'new Date (2017,3,1)', 'OB': 11}
{'date': 'new Date (2017,3,1)', 'Vehicular Accident': 119}
{'date': 'new Date (2017,3,1)', 'Fall': 8}
I tried to iterate the list dictionary and get the value of accident key, but no luck. I also tried replace(“””,”) in date value but still, it outputs a string. Hope you can help me. Thanks a lot.