0

I would like to use a configuration unique to the input of my script. e.x. if type = veh1 use config set for veh1 etc. I think the best way to tackle this is with dictionaries:

veh1 = {
"config_1":1,
"config_2":"a"
}
veh2 = {
"config_1":3,
"config_2":"b"
}

type = "veh1"

print(type["config_1"])

I would expect this to print 1, however I get an error instead because python is trying to slice the string veh1 as opposed to calling the dictionary named veh1

TypeError: string indices must be integers, not str

I've tried str(type) without success. I can iterate over the dictionary names with an if to set the config but that would be messy. Is there a way to force Python to interpret the variable name as a literal python string to call a dictionary or subroutine?

nate357159
  • 13
  • 2
  • 1
    your intended approach is bad. Make a dict of dicts or use `configparser` module and read configuration from file. – buran Feb 08 '21 at 20:21
  • also don't use `type` as name, it's a built-in function. – buran Feb 08 '21 at 20:22
  • 1
    Use a nested dictionary. And see https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables for some useful background on why that might be preferable – Brad Solomon Feb 08 '21 at 20:23

1 Answers1

2

You need to remove the brackets and add commas between the elements of the dictionary. So it will be like this:

veh1 = {
    "config_1":1,
    "config_2":"a"
}
veh2 = {
    "config_1":3,
    "config_2":"b"
}

type = veh1

print(type["config_1"])

As suggested by jarmod, you might want a dict of dicts like this:

dicts= {"veh1": {"config_1":1, "config_2":"a"}, "veh2": {"config_1":3, "config_2":"b"}}
type = "veh1"
print(dicts[type]["config_1"])
Marsolgen
  • 199
  • 1
  • 8
  • 1
    Not sure this is quite what the OP is looking for. The point is that `type` contains a string whose value is `"veh1"` or `"veh2"`, so the OP needs a dict of dicts. – jarmod Feb 08 '21 at 20:23