简体   繁体   中英

Last value onlyadded to a list

I am facing one issue to add element to my list

Here is my code

def summary(request,):
    data = []
    values = {}
    fruits =  ['apple','mango','orange','grapes']
    for i in fruits:
        values['fruits'] = i
        values['count'] = calculating_count(i)
        data.append(values)

What I am expecting is that my data list need to come like this

data = [{'fruits':apple,'count':10},
        {'fruits':mango,'count':20},
        {'fruits':orange,'count':30},
        {'fruits':grapes,'count':40}]

But what I am getting it as

data = [{'fruits':grapes,'count':40},
        {'fruits':grapes,'count':40},
        {'fruits':grapes,'count':40},
        {'fruits':grapes,'count':40}]

Only it appending the last element

def summary(request,):
    data = []
    fruits =  ['apple','mango','orange','grapes']
    for i in fruits:
        values = {}
        values['fruits'] = i
        values['count'] = calculating_count(i)
        data.append(values)

Simply,

def summary(request, ):
    fruits = ['apple', 'mango', 'orange', 'grapes']
    result = [{"fruits": fruit, "count": calculating_count(fruit)} for fruit in fruits]

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