Adding Key and Value inside a list of lists python

Question:

I have data that looks like this [[{'title': 'Line'}], [{'title': 'asd'}]]. I want to add a new key and value for every list inside of lists.

I have tried this but I’m having an error ‘list’ object is not a mapping. Any suggestion?

data = [[{'title': 'Line'}], [{'title': 'asd'}]]
titleID = [{'id': 373}, {'id': 374}]
combine = [{**dict_1, **dict_2}
           for dict_1, dict_2 in zip(char_id, data )]

the output I want is like this:

[[{'id': 373, 'title': 'Line'}], [{'id': 374, 'title': 'asd'}]]
Asked By: Gnani Kim

||

Answers:

Try this list comphrehension and unpacking

data = [[{'title': 'Line'}], [{'title': 'asd'}]]
titleID = [{'id': 373}, {'id': 374}]
[[{**i[0], **j}] for i,j in zip(data, titleID)]

Output

[[{'title': 'Line', 'id': 373}], [{'title': 'asd', 'id': 374}]]
Answered By: Deepak Tripathi

You can use list comprehension for a one-liner:

[[{**dict_1[0], **dict_2}] for dict_1, dict_2 in zip(data, titleID)]
Answered By: Anjaan

Because the elements of data are not dictionaries, but lists.
You can directly unpack nested iterable structures. See target_list for more details.

data = [[{'title': 'Line'}], [{'title': 'asd'}]]
titleID = [{'id': 373}, {'id': 374}]

print([[{**dict1, **dict2}] for [dict1], dict2 in zip(data, titleID)])

will work.
output:

[[{'title': 'Line', 'id': 373}], [{'title': 'asd', 'id': 374}]]

And if you are using Python 3.9+, you can use | operator for combining dictionaries.

print([[dict1 | dict2] for [dict1], dict2 in zip(data, titleID)])
Answered By: Boseong Choi
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.