简体   繁体   中英

Adding Items in a List to a Dictionary - Python

I am trying to add items to a list in a dictionary. I have two lists: x_list and y_list. I am trying to make x_list the keys and y_list the values. I have tried using a zip method but I really need to add them one by one. Right now I have:

dictionary = dict((x,0) for x in x_list)

but I would like to have something like:

dictionary = dict((x,y) for x in x_list, for y in y_list)

but obviously this is creating a syntax error. Is there any way to do this? Thank you!

EDIT:
I have tried zipping and it works, thank you, but I need to add the items to the dictionary one by one (I'm trying to have entries with the same keys add the values together for instance apple:10 and apple:5 become apple:15)

FOR EXAMPLE:

x_list = (blue, orange, purple, green, yellow, green, blue)
y_list = (1, 2, 5, 2, 4, 3, 8)

I would like the output to be

dictionary = {blue:9, orange:2, purple:5, green:5, yellow:4}

and the lists are continuously added to.

I would use a Counter here:

from collections import Counter

c = Counter()
for k, v in zip(x_list, y_list):
    c[k] += v

Try this:

dct = {}
x_list = (blue, orange, purple, green, yellow, green, blue)
y_list = (1, 2, 5, 2, 4, 3, 8)
for i in range(len(x_list)):
    if x_list[i] in dct.keys():
        dct[x_list[i]] += y_list[i]
    else:
        dct[x_list[i]] = y_list[i]

print dct

Short solution using enumerate function:

x_list = ['blue', 'orange', 'purple', 'green', 'yellow', 'green', 'blue']
y_list = [1, 2, 5, 2, 4, 3, 8]
result = {}

for i, v in enumerate(x_list):
    result[v] =  y_list[i] if not result.get(v) else result[v] + y_list[i]

print(result)

The output:

{'yellow': 4, 'orange': 2, 'blue': 9, 'green': 5, 'purple': 5}

Try this code:

list_x =["apple", "mango", "orange", "apple","mango"]
list_y = [10,5,25,10,15]
total_dict = {}
for k, v in zip(list_x, list_y):
    total_dict[k] = total_dict.get(k,0)+v 

The value of total_dict ends up as:

{'orange': 25, 'mango': 20, 'apple': 20}

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