简体   繁体   English

Python将带有普通键的列表添加到字典2

[英]Python Adding 2 list with common keys to dictionary

I am new to python. 我是python的新手。 I'm extracting two rows from a csvfile. 我要从csvfile中提取两行。

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']

And the quantity list corresponds to each of the items in its sequence. 数量清单按其顺序对应于每个项目。

Quantity = ['1,2,1','2,5','1,2']

How can i merge the two list with common keys into a dictionary? 我如何将两个具有公共密钥的列表合并到字典中? I tried splitting and joining but the quantity gets overwritten due to the common keys. 我尝试了拆分和合并,但是由于使用了公用密钥,所以数量被覆盖。

I am trying to output: 我正在尝试输出:

{'Apple: totalquantity','Banana: totalquantity', 
 'Carrot: totalquantity','Chocolate: totalquantity',
 'orange: totalquantity', 'strawberry: totalquantity'}

Please help! 请帮忙!

Will there be anyway where i can extract the csvfile row for the food items and assign its values in a dictionary? 无论如何,我可以在其中提取食品的csvfile行并在字典中分配其值吗?

for cvs file is as follows: 对于cvs文件如下:

row 1: apple, carrot, banana chocolate, apple strawberry, orange, carrot 第1行:苹果,胡萝卜,香蕉巧克力,苹果草莓,橙子,胡萝卜

row 2: 1,2,1 2,5 1,2 第2行:1,2,1 2,5 1,2

You can use Counter to aggregate the result: 您可以使用Counter汇总结果:

from collections import Counter

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
Quantity = ['1,2,1','2,5','1,2']
res = Counter()

for f_list, q_list in zip(Foodlist, Quantity):
    for f, q in zip(f_list.split(', '), q_list.split(',')):
        res[f] += int(q)

print(res)

Output: 输出:

Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1})

Use collections.default_dict to set up a dictionary to count your items in. 使用collections.default_dict设置一个字典来计算您的项目。

In [1]: from collections import defaultdict

In [2]: items = defaultdict(int)

In [3]: Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, or
   ...: ange, carrot']

In [4]: Quantity = ['1,2,1','2,5','1,2']

In [5]: for which, counts in zip(Foodlist, Quantity):
   ...:     foods = [w.strip() for w in which.split(',')]  # Split the foods and remove trailing spaces
   ...:     nums = [int(c) for c in counts.split(',')]  # Split the counts are convert to ints
   ...:     for f, n in zip(foods, nums):
   ...:         items[f] += n
   ...:

In [6]: items
Out[6]:
defaultdict(int,
            {'apple': 6,
             'banana': 1,
             'carrot': 2,
             'chocolate': 2,
             'orange': 2,
             'strawberry': 1})

In [7]:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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