简体   繁体   中英

Converting a list into a dictionary with multiple values using loops

I have a list of of string elements

marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]

I want to use a loop so that I can have a dictionary that looks like

dictionary= {'Bill': [50,70,90, 65, 81] , 'Jack': [80,95,100, 98, 72]}

The values should also be turned into floating values because I want to find the averages but I haven't gotten there yet.

This is what I have so far:

dictionary ={}
for items in marks:
    c = items.split(', ')
    for a in range(len(c)):
        dictionary[c[0]] = c[a]
print(dictionary)

And it prints {'Bill': '81' , 'Jack': '72'}

The issue here is that I only get one value per key in my dictionary and it's the last value of the list and I understand it's because the dictionary[c[0]]= c[a] just replaces the previous one.

How do I go about so that the key can get multiple values without each previous value being changed in the loop?

Please let me know if loops are inefficient in doing this, but it is the only method I am comfortable doing at the moment.

Thanks!

dictionary[c[0]] = c[a] because of this, only the last value is added to the list. In order to add all values, you need to use append() . To convert to float, use float() . Corrected code:

dictionary ={}
for items in marks:
    c = items.split(', ')
    dictionary[c[0]] = []
    for a in range(len(c)):
        dictionary[c[0]].append(float(c[a]))
print(dictionary)

It is probably easy to unpack the key with:

key, *rest = items.split(', ')

This will give you the rest of the items in rest to process as you see fit (a list comprehnsion being a particularly Pythonic way) and avoiding the indexing and for loop altogether:

marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]

d = {}
for s in marks:
    key, *rest = s.split(', ')
    d[key] = [float(n) for n in rest]
    

Leaving you with:

{'Bill': [50.0, 70.0, 90.0, 65.0, 81.0],
 'Jack': [80.0, 95.0, 100.0, 98.0, 72.0]}
marks = ["Bill, 50, 70, 90, 65, 81", "Jack, 80, 95, 100, 98, 72"]
    
out = {name: [*map(int, grades)] for name, *grades in map(lambda m: m.split(','), marks)}
print(out)

Prints:

{'Bill': [50, 70, 90, 65, 81], 'Jack': [80, 95, 100, 98, 72]}

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