0

This might be simple, but I'm stuck. I have globals() that creates dictionaries based on zipping lists (that will differ in sizes, thus differ in the number of the dictionaries that get created). The new dictionaries that get created look like the below:

dict0 = {foo:bar}
dict1 = {more_foo:more_bar}

How do I call these new dictionaries in a for loop?

I want my script to do the below:

for i in (dict0, dict1):

The only issue is that the number of dictx (dictionaries) will differ based on the inputs from the script.

martineau
  • 119,623
  • 25
  • 170
  • 301
JackFrost
  • 7
  • 1
  • 3
    This seems like an xy problem. Anytime you are making variables with name like `dict0` and `dict1`, you almost certainly should be using a list of dicts and then using `dicts[0]` `dicts[1]`. Then this problem evaporates. – Mark Apr 17 '21 at 16:11
  • 3
    When the number of things is dynamic, that's when you put them in lists or dictionaries. – Barmar Apr 17 '21 at 16:13
  • Probably a duplicate of [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – martineau Apr 17 '21 at 17:08

2 Answers2

0

As nicely put in comments, in your case, you should append the dictionaries to a list:

list_iterator = list()
# create dict 1. 
list_iterator.append(dict1)
# create dict 2. 
list_iterator.append(dict2)
# and so on. If your dict create algorithm is repetetive, you can add the append command to the end.
user3243944
  • 103
  • 7
  • This gives me a list of dictionary names instead of calling the actual dictionaries. I think I have to use a combination of locals() along w/ range and len of a list that matches the number of dictionaries. – JackFrost Apr 17 '21 at 16:44
  • It shouldn't if you do not append with "dict1", loose the "" marks. list_iterator.append(dict1), not list_iterator.append("dict1") – user3243944 Apr 17 '21 at 16:45
-1

I figured it out...

for i in range(len(someList)):
    dicts = locals()['dict' + str(i)]
JackFrost
  • 7
  • 1