0

Python 3.7 question: I need to make 120 dictionaries from a list of 120 unique names (which are strings). Once these dictionaries are created, i will fill them with data. My question is: Is there a way i can loop through the list of 120 strings and create 120 empty dictionaries, each of which has that string for its name?

Thank you.

Sal
  • 3
  • 2
  • To state explicitly something that's often only implied in answers (both here and in the duplicate question), it's a bad idea to create actual variables from a list of names (and a dictionary is better). The reason is that variable names are not data. They're for the programmer to use and reason about. If they're just data, they should be in a data structure, like a dictionary, where you have better tools to contain them and write code to use them. If you have 120 names, it is extremely unlikely that you will know them all well enough to use them directly in your code. – Blckknght Sep 06 '20 at 10:16
  • @Blckknght. Thanks very much for your feedback. You have a good point. – Sal Sep 06 '20 at 11:07

1 Answers1

0

here is a dict of dict from a list of var names with empty {}:

s = ['d1', 'd2', 'd3']

tmp=dict()    
for (e) in s:
    tmp['{}'.format(e)] = dict()

print(tmp)

OUTPUT:

{'d1': {}, 'd2': {}, 'd3': {}}

EDIT:

To access the inner dict:

print(temp['d1'])  # {}

EDIT 2:

Shorter way without formatting (thanks to @Blckknght)

for (e) in s:
    temp[(str(e))] = {}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • Thanks. Follow-up question: I can't seem to access the inner dictionaries in the usual manner. Because ultimately that's what i need to do: call up the inner dictionaries and fill them up with data. – Sal Sep 06 '20 at 09:50
  • @Sal edited for it. – DirtyBit Sep 06 '20 at 09:58
  • 1
    You've got a lot of unnecessary stuff in this code. You can just use `tmp[e] = {}` rather than doing formatting and calling `dict` by name. If the `s` list could contain non-strings, `str(e)` makes more sense than using `str.format`. – Blckknght Sep 06 '20 at 10:05