johneth
johneth

Reputation: 2928

Appending something to a list within a dict within a list in Python

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:

  1. Check to see if a dict with a specific id exists in the list already
  2. If a dict containing that id exists, append something to it's embedded_list
  3. If a dict containing that 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

Answers (2)

bpgergo
bpgergo

Reputation: 16037

or just a simple dic

{
  '234nj233nkj2k4n52' : [],
  'jb234bhj23423h4b4' : []
}

Upvotes: 1

Sven Marnach
Sven Marnach

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

Related Questions