I’m having a list of dictionaries that looks like this:
[{
'Host-id': 'W000644',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
},
{
'Host-id': 'W000955',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
},
{
'Host-id': 'K000003',
'Email': 'Gmail',
'Color': 'green',
'Timestamp': '15-11-2021'
},
'Host-id': 'G000004',
'Email': 'Colemail',
'Color': 'blue',
'Timestamp': '14-11-2021'
},
{
'Host-id': 'S000002',
'Email': 'Gmail',
'Color': 'blue',
'Timestamp': '22-10-2021'
},
{
'Host-id': 'G000003',
'Email': 'spam',
'Color': 'red',
'Timestamp': '12-11-2021'
}]
I want to group it, using the first letter of the ‘Host-Id’ Value (like ‘W’ for Water or ‘G’ for Gas) so it looks finally like this:
{
"Water": [
{
'Host-id': 'W000644',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
},
{
'Host-id': 'W000955',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
}
],
"Gas":[
{
'Host-id': 'G000004',
'Email': 'Colemail',
'Color': 'blue',
'Timestamp': '14-11-2021'
},
{
'Host-id': 'G000003',
'Email': 'spam',
'Color': 'red',
'Timestamp': '12-11-2021'
}
]
}
Unfortunately I have no idea where to start. I have tried it with a loop but it looks overly complex and didnt yield the results I wanted. Could anyone please point me into the right direction?
Thank you in advance
A
>Solution :
I can recommend PyFunctional library for your task. It could be done without loops like this
from functional import seq
lst = [
{
'Host-id': 'W000644',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
},
{
'Host-id': 'W000955',
'Email': 'Hotmail',
'Color': 'red',
'Timestamp': '12-10-2021'
},
{
'Host-id': 'G000004',
'Email': 'Colemail',
'Color': 'blue',
'Timestamp': '14-11-2021'
},
{
'Host-id': 'G000003',
'Email': 'spam',
'Color': 'red',
'Timestamp': '12-11-2021'
}
]
KEY_MAP = {
"W": "Water",
"G": "Gas",
}
s = seq(lst)
res = s.group_by(lambda x: KEY_MAP[x['Host-id'][0]])
print(res.to_dict())
Output
{
'Water': [
{'Host-id': 'W000644', 'Email': 'Hotmail', 'Color': 'red', 'Timestamp': '12-10-2021'},
{'Host-id': 'W000955', 'Email': 'Hotmail', 'Color': 'red', 'Timestamp': '12-10-2021'}
],
'Gas': [
{'Host-id': 'G000004', 'Email': 'Colemail', 'Color': 'blue', 'Timestamp': '14-11-2021'},
{'Host-id': 'G000003', 'Email': 'spam', 'Color': 'red', 'Timestamp': '12-11-2021'}
]
}