Home > Software engineering >  Dictionary gives "TypeError: string indices must be integers" when i pass it as an argumen
Dictionary gives "TypeError: string indices must be integers" when i pass it as an argumen

Time:10-08

I manage to send this json to my server:

data  =  {'transformations': '{"translate":{"z":-1.2,"y":-3,"x":-2},"scale":{"y":2,"z":2,"x":2},"rotate":{"x":90,"z":20,"y":80}}', 'part_id': 'cube10mm', 'printing_settings': '{"infill_pattern":"grid","top_layers":6,"wall_line_count":3,"bottom_layers":6,"layer_height":0.5,"infill_density":90}', 'annotations': '{"load":[],"anchor":[]}'}

When i type print(type(data)) i get <class 'dict'>

Then i call a function and pass it this json as an argument:

outcome = myfunction(data)

I get this error: TypeError: string indices must be integers in this line: layer_height = params_dict["printing_settings"]["layer_height"]

I tried this as well:

layer_height = int(params_dict["printing_settings"]["layer_height"])
layer_height = float(params_dict["printing_settings"]["layer_height"])

What's even stranger is that i get this error even when i try to print the details about params_dict["printing_settings"]["layer_height"].

For example, when i use:

print(type(params_dict["printing_settings"]["layer_height"]))

or

print(params_dict["printing_settings"]["layer_height"])

These two lines give me the same error as well. At this point, i am stuck.

CodePudding user response:

I think your problem is that you have the sub_dictionaries as string e.g Try this

{"translate":{"z":-1.2,"y":-3,"x":-2},"scale":{"y":2,"z":2,"x":2},"rotate":{"x":90,"z":20,"y":80}}

instead of this

'{"translate":{"z":-1.2,"y":-3,"x":-2},"scale":{"y":2,"z":2,"x":2},"rotate":{"x":90,"z":20,"y":80}}'

CodePudding user response:

You need to change your string to dict:

layer_height = json.loads(data["printing_settings"])["layer_height"]

or

import ast

for k, v in data.items():
    if isinstance(v, str) and "{" in v:
        data[k] = ast.literal_eval(v)

data
  • Related