简体   繁体   中英

Pythonic way of editting list of dictionaries

I write the code which works for me. But I wonder if I could write in a better way.

My purpose is find first elements in dataR which value of "col" key is equal to dataS element and adding 1 to value of "quan" key . dataR is a list of dictionaries. dataS is a list.

for item in dataS:
    dataR[dataR.index(next(x for x in dataR if x['col']==item))].['quan'] += 1

You don't need to lookup the row by index, you already have it:

for item in dataS:
    first_row = next(row for row in dataR
                     if row['col'] == item)
    first_row['quan'] += 1

dataR is the name for a sequence of dict objects. first_row is a name we give to one of the objects in the sequence. If we modify that object using that name we will modify the object in the sequence named dataR . No copies are made. In python to make a copy of an object you usually have to be explicit.

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