Assign list values to dictionaries

Viewed 127

I have a list prices:

prices = [0.9986, 0.8065, -0.1779, 0.8065]

and a list of dictionaries mydicts:

mydicts = [{'name':'Food1'}, {'name':'Food2'}, {'name':'Food3'}, {'name':'Food4'}]

Now I need to pass each item of price as value for key price in each dictionary, this would be the result:

mydicts = [
    {'name':'Food1', 'price':0.9986}, 
    {'name':'Food2', 'price':0.8065}, 
    {'name':'Food3', 'price':-0.1779}, 
    {'name':'Food4', 'price':0.8065}
    ]

In order to do this, I'm iterating over the list and the list of dictionaries and asigning each value of the list to the dictionary:

for price, dictionary in zip(prices, mydicts):
    dictionary['price'] = price

I was wondering if there is a more efficient way of doing this, In my case I have to asign lots of values to the list of dictionaries and I'm not sure if this is the most efficient way.

2 Answers

There's nothing wrong with your solution. It's O(n), which is as efficient as possible, and it's simple and short.

There isn't anything more efficient than an O(n) approach since you have to touch each index to create each element.

Related