Reputation: 2928
I am attempting to create a list
of dicts
which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
dict
with a specific id
exists in the list alreadyid
exists, append something to it's embedded_list
id
does not exist, create a dict, append it to the list.I am aware of being able to test if a dict
exists in a list
based on something inside that dict
using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list
within a dict
within a list
efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Upvotes: 0
Views: 244
Reputation: 16037
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}
Upvotes: 1
Reputation: 601441
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list)
:
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
Upvotes: 4