简体   繁体   中英

Create a list of dictionaries with values from another list in Python

I have a list of values that looks like this: values = [2.5,3.6,7.5,6.4] , Is it possible to create several dictionaries with the values from this list and the same key value for all items, so the final output will look like this:

list_of_dic = [{'interest rate':2.5}, {'interest rate'}:3.6, {'interest rate':7.5}, {'interest rate':6.4}]

Sure, just make a second table "labels" with your labels.

Then:

def f(labels, values):
    l = [] # here is the result list you want to fill with dicts
    foreach i in range(0, len(values)): # for each value
        d = dict{} # create dict
        d[values[i]] = labels[i] # put your key and value in it
        l.append(d) # add it to your result list
    return l # return the result list

You can achieve this by using list comprehension:

return [{'interest rate': val} for val in values]

or

a = []
    for val in values:
        a.append({
            'interest rate':val
        })
        
    return a

Both do the same thing

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