Python create list of dicts

Question:

I am new to python and I am trying to construct data structure from existing data.

I have following:

[
    {'UserName': 'aaa', 'AccessKeyId': 'AKIAYWQTISJD6X27YVK', 'Status': 'Active', 'CreateDate': datetime.datetime(2022, 9, 8, 15, 56, 39, tzinfo=tzutc())},
    {'UserName': 'eee', 'AccessKeyId': 'AKIAYWQTISJD6QXMAKY', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 12, 30, 59, tzinfo=tzutc())}, 
    {'UserName': 'eee', 'AccessKeyId': 'AKIAYWQTISJDUARK6FV', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 16, 58, 38, tzinfo=tzutc())}
]

I need to get this:

{
  "aaa": [
    {'AccessKeyId': 'AKIAYWQTISJD6X27YVK', 'Status': 'Active', 'CreateDate': datetime.datetime(2022, 9, 8, 15, 56, 39, tzinfo=tzutc())}],
  "eee": [
    {'AccessKeyId': 'AKIAYWQTISJD6QXMAKY', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 12, 30, 59, tzinfo=tzutc())}, 
    {'AccessKeyId': 'AKIAYWQTISJDUARK6FV', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 16, 58, 38, tzinfo=tzutc())}
   ]
}

I tried following:

list_per_user = {i['UserName']: copy.deepcopy(i) for i in key_list} 
for obj in list_per_user:     
   del list_per_user[obj]['UserName'] 

but I am missing array here. So in case of two keys per user I will have only last one with this. I don’t know how to get the list I need per user.
Thanks!

Asked By: opti2k4

||

Answers:

Create an external dict that maps username -> list of entries.

data = [
    {'UserName': 'aaa', 'AccessKeyId': 'AKIAYWQTISJD6X27YVK', 'Status': 'Active', 'CreateDate': datetime.datetime(2022, 9, 8, 15, 56, 39, tzinfo=tzutc())},
    {'UserName': 'eee', 'AccessKeyId': 'AKIAYWQTISJD6QXMAKY', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 12, 30, 59, tzinfo=tzutc())}, 
    {'UserName': 'eee', 'AccessKeyId': 'AKIAYWQTISJDUARK6FV', 'Status': 'Active', 'CreateDate': datetime.datetime(2023, 1, 24, 16, 58, 38, tzinfo=tzutc())}
]

new_data = {}
for entry in data:
    new_data.setdefault(entry["UserName"], []).append(
        {k: v for k, v in entry.items() if k != "UserName"}
    )

print(new_data)

Output (some fields hidden because I don’t want to import those libraries in my repl, but they’ll be there when you run it)

{'aaa': [{'AccessKeyId': 'AKIAYWQTISJD6X27YVK', 'Status': 'Active'}],
 'eee': [{'AccessKeyId': 'AKIAYWQTISJD6QXMAKY', 'Status': 'Active'},
         {'AccessKeyId': 'AKIAYWQTISJDUARK6FV', 'Status': 'Active'}]}
Answered By: Samathingamajig
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.