Python add list of objects as dict value

Advertisements

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:

 {'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.

Leave a Reply Cancel reply