Python, Flask - TypeError: string index indices must be integers or slices, not str

Viewed 106

Goal: Print out the values of a dictionary via a for loop

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

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?

1 Answers

Let's break the answer in two.

First, to "Print out the values of a dictionary via a for loop" , as requested, you just do:

for k in serializable_format:
    print(serializable_format[k]

the loop iterates over the keys of the dictionary. You should check the official documentation on dicts, particularly the "Looping Techniques" part. You will find the use of dict.items() useful.

The problem in your code 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 some other type (like dicts), that can be accessed via keys (like 'pre_transactions'). Maybe your dictionary should not be a dictionary of strings but of another kind of objects.

Note that your code has one loop nested inside another, so for each key you loop again.

Related