nate357159
nate357159

Reputation: 13

Call a dictionary name with a variable python 3

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?

Upvotes: 0

Views: 1096

Answers (1)

Marsolgen
Marsolgen

Reputation: 187

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"])

Upvotes: 1

Related Questions