-1

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.

jarmod
  • 71,565
  • 16
  • 115
  • 122
Virgilio
  • 41
  • 1
  • 9
  • 3
    "I'd like to call a variable with a number in the name." - don't. Use a list. – user2357112 Dec 01 '20 at 18:50
  • Why not just `for tempDict in [dict0, dict1, dict2]:`? – Cory Kramer Dec 01 '20 at 18:51
  • 2
    Whenever you have a variable list of things (like tables that are numbered 0,1,2,...,n) and you are tempted to create variables such as dict0, dict1, dict2, etc. just imagine that `n` is very large, like a million. Would you create 1 million variables named dict0, dict1, ..., dict999999? No, you wouldn't. That's how you know that you need to use something else and that's typically a list (if you can index numerically and sequentially) or a dictionary (otherwise). – jarmod Dec 01 '20 at 18:55
  • 1
    @jarmod That's a brilliant way to put it. – Jab Dec 01 '20 at 18:56

2 Answers2

1

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

JBirdVegas
  • 10,855
  • 2
  • 44
  • 50
0

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

d4riush
  • 370
  • 3
  • 8