[英]Python, Flask - TypeError: string index indices must be integers or slices, not str
Goal: Print out the values of a dictionary via a for loop目标:通过 for 循环打印出字典的值
Here is a recreated version of the code as reference (not the actual code, works just the same):这是代码的重新创建版本作为参考(不是实际代码,工作方式相同):
import networkx as nx
random_dictionary = {
"name": "DAG",
"children": "None",
"father": "None",
"mother": "None",
"spouse": "None",
}
serializable_format = random_dictionary
for n in serializable_format:
print("[+] node: " + n + ", edge: " + str(serializable_format[n]['pre_transactions']))
for x in serializable_format[n]['pre_transactions']:
ledger.add_edge(n, x)
When I execute it, I am constantly met with the following error...当我执行它时,我经常遇到以下错误......
TypeError: string index indices must be integers or slices, not str
I can not insert an integer in the [n]
section, as that would give me the following error我无法在
[n]
部分插入 integer,因为这会给我以下错误
KeyError: (insert any number here)
So how do I go about making a for loop which gets the content from the dictionary without encountering any errors?那么我该如何做一个for循环来从字典中获取内容而不会遇到任何错误呢?
The problem is that serializable_format[n]
is a string ("DAG", 'None", etc). The expression serializable_format[n]['pre_transactions']
tries to use the string 'pre_transactions'
for indexing the first string, raising a TypeError
. Re-check your code, because you are mistaken those strings with sone other type (like dicts).问题是
serializable_format[n]
是一个字符串(“DAG”、“None”等)。表达式serializable_format[n]['pre_transactions']
尝试使用字符串'pre_transactions'
来索引第一个字符串,从而引发TypeError
. 重新检查您的代码,因为您将这些字符串误认为是其他类型(如 dicts)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.