0

I have like 10 dictionaries and I want to print all the dictionaries with all the keys inside.

Dict1 = {}
...
Dict10 = {}

We could do:

print(list(Dict1.keys()))
...
print(list(Dict10.keys()))

But is there a code more simple to do this? Like a for loop? I'm working on a project where:

  1. Operator types get_report
  2. The program looks for all dictionaries in another .py file and print all the keys from every dictionary
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    put your dicts into a list. then iterate over the list. you gain nothing by having N variables named dict1... dictN – timgeb Feb 04 '22 at 08:13
  • 1
    You shouldn't have 10 variables. Use a dict of dicts or list of dicts. Check https://stackoverflow.com/q/1373164/4046632 – buran Feb 04 '22 at 08:16
  • And by the way, - _The program looks for all dictionaries in another .py file and print all the keys from every dictionary_ - depending on the use case you may be better using JSON if the only purpose of the second py fie is to define bunch of dicts. – buran Feb 04 '22 at 08:28

1 Answers1

1

In python globals() store all variable as a dictionary

dict1 = {1: 1, 2: 2}
dict2 = {6: 1, 7: 2}
dict3 = {4: 1, 3: 2}
var = globals()

for i in range(1, 11):
    dict_name = f"dict{i}"
    if var.get(dict_name):
        keys = var[dict_name].keys()
        print(list(keys))

@timegb suggested this might get crashed. So better approach to use dict.get to handle unknown keys

Mazhar
  • 1,044
  • 6
  • 11
  • 3
    technically correct, but bad coding style. for example, this code crashes if there aren't exactly ten dicts. – timgeb Feb 04 '22 at 08:16
  • 1
    The main problem is that it rely on `globals()`. This should be proper nested data structure. – buran Feb 04 '22 at 08:31