简体   繁体   中英

Output a dictionary based on inputs from another dictionary and two lists

I have a dictionary and two lists and would like to output another dictionary that contains the individual list as the title and sum of the list contents as the values however, I have no clue as to how I could do this.

results = {'Apple':'14.0', 'Banana':'12.0', 'Orange':'2.0', 'Pineapple':'9.0'}

ListA = ['Apple','Pineapple']
ListB = ['Banana','Orange']

Output:

dicttotal = {'ListA':'23.0', 'ListB':'14.0'}

Edit: I have decided to use pandas to work with the above data as I find that the simplicity of pandas is more suited for my level of understanding. Thanks for the help everyone!

in python you can use list comprehensions to make this easy to read:

items_for_a = [float(v) for i, v in results.items() if i in ListA]
total_a = sum(items_for_a)

the dicttotal you want to print is strange, though. I don't think you want to print variable names as dictionary keys.

in python2 you should use .iteritems() instead of .items()

You can use fllowing code get ListA's sum. The same way for ListB. Just try it yourself

dicttotal = {}
ListASum = 0.0
ListBSum = 0.0
for item in ListA:
    if item in results:
        ListASum += float(results[item])
dicttotal['ListA'] = ListASum

Reduce and dictionary comprehension to create dictionary with an initial value, followed by updating a single value. Had key names not been variable names maybe could have done dict comprehension for both.

from functools import reduce
d_total = {'ListA': str(reduce(lambda x, y: float(results[x]) + float(results[y]), lista))}
d_total['ListB'] = str(reduce(lambda x, y: float(results[x]) + float(results[y]), listb))
 {'ListA': '23.0', 'ListB': '14.0'} 

Note: PEP-8 snake_case for naming

一线使用(丑陋的) eval()函数,但是正如Eduard所说,最好不要将变量名用作键:

{list_name: str(sum([float(results[item]) for item in eval(list_name)])) for list_name in ['ListA', 'ListB']}

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