Home > Software engineering >  Python add list of objects as dict value
Python add list of objects as dict value

Time:03-09

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 :(

CodePudding user response:

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.

CodePudding user response:

try this

for item in my_list:
    message['data']  = [{'text': item[0], 'value': item[1]}]

It appends the item to the message['data'] list by using python's operator for lists.

  • Related