3

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'}]]
1
  • 1
    what's your expected output Commented Oct 31, 2022 at 7:53

3 Answers 3

1

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}]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use list comprehension for a one-liner:

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

Comments

1

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)])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.