Concatenate iterator to variable name

506 Views Asked by At

I'd like to call a variable with a number in the name. I think the closest I've come is concatenating an iterator onto the name, and casting that as a dictionary but it doesn't work.

This is what I have tried:

dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}

for i in range(3):
    tempDict = "dict"+str(i) # type is string
    print(dict(tempDict))

output: ValueError: dictionary update sequence element #0 has length 1; 2 is required

These dictionaries are being populated with a database call, and the tables are numbered 0,1,2...n. Some days I have one dictionary, and some days multiple. It would be really convenient to be able to call them and act on the contents iteratively if possible. I'm not sure what to google for an answer, thank you in advance.

2

There are 2 best solutions below

0
On

Assuming you have created the variables with the correct names (in this case dict0, dict1, dict2) you can get the values via their name using the vars() method

dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}

for i in range(3):
    print(vars()[f"dict{i}"])

This prints each dict as expected

0
On

if you want to access dictionaries by their variable name try this:

dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}

for i in range(3):
    dict_var_name = "dict"+str(i) # type is string
    print(globals()[dict_var_name])

globals() return a dictionary which caontain all defined variables in global scope. for more information on this look at this question