Reputation: 35
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!
Upvotes: 2
Views: 139
Reputation: 195508
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]}
Upvotes: 1
Reputation: 92450
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]}
Upvotes: 1
Reputation: 8101
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)
Upvotes: 1