简体   繁体   中英

How to loop in Python to update a dictionary?

I have the following dicts:

{'company':'a', 'op':'buy', 'value':10}, 
{'company':'b', 'op':'buy', 'value':15},
{'company':'a', 'op':'sale', 'value':5}

... and I want a new updated dict to be generated

{'company':'a', 'value':5}, 
{'company':'b', 'value':15}

Note that if a sale has been made, it calculates to update 'value'.

I hope someone guides me to a solution!Thanks

if you want to delete 'op' field, use del dict['op'] if you want to update 'value' field, use dict['vp'] = x for using a loop to update all dicts, you might need a list to store all the new values ordered by the dicts you want to update, and also have a list to store your current dicts, and update them. sample code

updates = [5,10,15]
dicts = [{'company':'a', 'value':5, 'op':'buy'},{'company':'b', 'value':15, 'op':'sale'},.{'company':'c', 'value':20, 'op':'buy'}]
for i,update in enumerate(updates):
    del dicts[i]['op']
    dicts[i]['value'] = update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM