Python 字符串索引必须是整数而不是 str 字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18015385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:43:24  来源:igfitidea点击:

string indices must be integers not str dictionary

pythonpython-2.7

提问by Simon K Bhatta4ya

I am trying to get value form a list in a dict? not sure how it can be accessed? but here's what I did & I'm getting a error as TypeError: string indices must be integers, not str

我想从字典中的列表中获取价值?不确定如何访问它?但这是我所做的 & 我收到了一个错误,因为 TypeError: 字符串索引必须是整数,而不是 str

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

for i in alice:
    print i['quizzes']

I'm learning python, & I had few more queries If anyone could help would be a gr8 help in learning.Thanks in advance.

我正在学习 python,我有更多的疑问如果有人可以提供帮助,将是学习中的 gr8 帮助。提前致谢。

1) How to access the key 'homework' & sum its value in list?

1)如何访问关键的“作业”并将其值汇总到列表中?

2) How to access dict alice & sum its values of all keys? homework + quizzes + tests with sum() function

2) 如何访问 dict alice 并将其所有键的值相加?作业 + 测验 + 使用 sum() 函数进行测试

3) How to access the key 'llyod' & get its len() of a list? say 'homework'

3) 如何访问键 'llyod' 并获取列表的 len()?说“作业”

this is what I tried & I got the same error for this one as well:

这是我尝试过的,我也遇到了同样的错误:

def average(x):
    for a in x: 
       return sum(a['homework']) / len(a['homework'])
       return sum(a['quizzes']) / len(a['quizzes'])
       return sum(a['tests']) / len(a['tests'])

If anyone could please clear my doubts on those above 3 question.

如果有人可以请清除我对上述 3 个问题的疑虑。

采纳答案by suhailvs

question1(How to access the key 'homework' & sum its value in list?)

问题 1(如何访问关键的“作业”并在列表中求和它的值?)

>>> sum(lloyd['homework'])
354.0

question2 homework + quizzes + tests

问题 2 作业 + 测验 + 测试

def findsum(x):
    return sum([sum(x['homework']),sum(x['quizzes']),sum(x['tests'])])

>>> findsum(lloyd)
741.0

question3) How to access the key 'llyod' & get its len() of a list? say 'homework'

问题 3)如何访问密钥 'llyod' 并获取列表的 len()?说“作业”

>>> len(lloyd['homework'])
4

回答by Jblasco

This code:

这段代码:

 for i in alice:
        print i['quizzes']

takes the dictionary Alice and goes iterating on its keys, which are strings. I think what you want is:

获取字典 Alice 并对其键进行迭代,这些键是字符串。我想你想要的是:

print alice['quizzes']

回答by Martijn Pieters

You are looping over the keysof alice, not the values. Your keys are strings. Even if you were looping over the values, none of the values in alicecan be indexed by 'quizzes'. You could just print alice['quizzes'], but that is probably not what you wanted to start with.

您遍历了钥匙alice,而不是值。你的钥匙是字符串。即使您正在遍历这些值, 中的任何值alice都不能由'quizzes'. 您可以只打印alice['quizzes'],但这可能不是您想要开始的。

You want to put all your named dictionary into one 'parent' dictionary instead:

您想将所有命名字典放入一个“父”字典中:

students = {
    "lloyd": {
        "name": "Lloyd",
        "homework": [90.0, 97.0, 75.0, 92.0],
        "quizzes": [88.0, 40.0, 94.0],
        "tests": [75.0, 90.0]
    },
    "alice": {
        "name": "Alice",
        "homework": [100.0, 92.0, 98.0, 100.0],
        "quizzes": [82.0, 83.0, 91.0],
        "tests": [89.0, 97.0]
    },
    "tyler": {
        "name": "Tyler",
        "homework": [0.0, 87.0, 75.0, 22.0],
        "quizzes": [0.0, 75.0, 78.0],
        "tests": [100.0, 100.0]
    },
}

Now you can loop over thisdictionary and access various keys per student:

现在你可以遍历这个字典并访问每个学生的各种键:

for student_data in students.values():
    print student_data['quizzes']

Note the use of .values()here to loop over justthe values of the studentsdictionary, as we don't use the keys here.

请注意使用.values()here循环students字典的值,因为我们在这里不使用键。

Use the same loop to calculate your averages, but remember that a function endswhen a returnstatement is encountered. You can always return multiple values from a function by returning a tuple:

使用相同的循环来计算平均值,但请记住,当遇到语句时,函数将结束return。您始终可以通过返回元组从函数返回多个值:

def average(student):
    homework = ...
    quizzes = ...
    tests = ....
    return (homework, quizzes, tests)

or you could use a dictionary, for example.

或者你可以使用字典,例如。

回答by lara

better, that you use the iteration over both (key and value). It is more generally. Try it, it works:

更好的是,您对(键和值)都使用迭代。这是更普遍的。试试看,它有效:

values_of_alice=[]
for key, value in students.iteritems():
    if key == 'alice':
        values_of_alice.append(value)
for key2, value2 in values_of_alice[0].iteritems():
           if key2 == 'quizzes':
               print value2