如何在列出python的字典中迭代一堆值

问题描述 投票:-2回答:1

ratinglist = open("ratings.txt").readlines()

booklist = open("booklist.txt").readlines()

keys = [key.strip('\n') for key in ratinglist[0::2]]

values = [value.strip(' \n').split(' ') for value in ratinglist[1::2]]


my_dict = dict(zip(keys, values))


for values in my_dict:
    value * x = sum

所以,我有一个巨大的字典,其中包含每个键的值列表。

这是我的字典的一个例子:

'KeeLed': ['0', '0', '0', '5', '0', '0', '0', '5', '0', '5', '5', '0', '0', '0', '0', '0', '5', '-3', '-3', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '5', '0', '0', '5', '0', '5', '5', '5', '5', '0', '0', '0', '0', '0', '3', '1', '0', '0', '0', '0'], 'Megan': ['5', '5', '0', '0', '0', '0', '0', '0', '0', '3', '0', '5', '0', '0', '1', '0', '5', '0', '1', '5', '0', '0', '0', '0', '0', '1', '0', '5', '0', '0', '3', '5', '5', '0', '0', '5', '0', '0', '3', '0', '0', '3', '5', '5', '0', '0', '0', '0', '0', '5', '5', '0', '5', '0', '0']}

我需要做的是一个for循环,循环遍历每个值,将它们相乘,然后相加。

我只需要帮助,即可使for循环正确遍历这些值。

例如,对于KeeLed和Megan,我希望此for循环迭代它们各自的值列表,并将它们相乘,然后相加。

例如:0 * 5,+ 5 * 0,+ 0 * 0,+ 5 * 0 ...等等,等等

问题是,关于如何遍历dictionary内的列表,我还没有在网上找到任何东西。我已经找到了一些遍历列表的资源,但是我需要遍历字典内的值列表。

我希望将结果放入列表中,但是如果在for循环中获得了一些帮助,我可以这样做。

scores for each person = [325, 450]
python arrays dictionary
1个回答
0
投票

“问题是,我没有在网上找到任何有关如何遍历字典内列表的内容。我发现了一些遍历列表的资源,但我需要遍历内部值的列表字典的内容。“

示例

myDict = {

'KeeLed': ['0', '0', '0', '5', '0', '0', '0', '5', '0', '5', '5', '0', '0', '0', '0', '0', '5', '-3', '-3', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '5', '0', '0', '5', '0', '5', '5', '5', '5', '0', '0', '0', '0', '0', '3', '1', '0', '0', '0', '0'], 
'Megan': ['5', '5', '0', '0', '0', '0', '0', '0', '0', '3', '0', '5', '0', '0', '1', '0', '5', '0', '1', '5', '0', '0', '0', '0', '0', '1', '0', '5', '0', '0', '3', '5', '5', '0', '0', '5', '0', '0', '3', '0', '0', '3', '5', '5', '0', '0', '0', '0', '0', '5', '5', '0', '5', '0', '0']

}

# For-looping through dict will give the key.
for name in myDict:

  total = 0

  # applying the key into myDict will give the list associated with the dict
  for score in myDict[name]:

    total = total + int(score)

  print(name,total)

结果

KeeLed 54
Megan 85
© www.soinside.com 2019 - 2024. All rights reserved.