简体   繁体   English

使用循环将列表转换为具有多个值的字典

[英]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'}它打印{'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.这里的问题是我的字典中的每个键只有一个值,它是列表的最后一个值,我理解这是因为dictionary[c[0]]= c[a]只是替换了前一个值。

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. dictionary[c[0]] = c[a]因此,只有最后一个值被添加到列表中。 In order to add all values, you need to use append() .为了添加所有值,您需要使用append() To convert to float, use float() .要转换为浮点数,请使用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:这将使您可以按照您认为合适的方式处理rest的其余项目(列表理解是一种特别的 Pythonic 方式)并完全避免索引和for循环:

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]}

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

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