Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python add list of objects as dict value

everybody!
I think it is very simple, but I have no idea how to do that.
I have an dict:

 message = {'message': 'bla bla bla', 'data':[]}

and a list:

 my_list = [('a', 1), ('b', 2)]

I want to append data from the list to the dict. My dict eventually should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {'message': 'bla bla bla', 'data':[{'text': 'a', 'value': 1}, {'text': 'b', 'value': 2} ]}

I tried to do something like that:

 for item in my_list:
      message['data'][array.index(item)] = {'text': item[0], 'value': item[1]}

but it’s not working 🙁

>Solution :

You can do this in one simple line:

message['data'].extend({'text': t, 'value': n} for t, n in my_list)

The generator expression creates a sequence of the desired dict values, and extend appends them to message['data'] one at a time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading