vlaaaaaddd
vlaaaaaddd

Reputation: 21

Creating python dictionaries using for loop

I make a bunch of matrices that I want to store in python dictionaries and I always find myself typing the same thing for every state that I want to build, i.e.

Ne21_1st_state = {}
Ne21_2nd_state = {}
Ne21_3rd_state = {}
Ne21_4th_state = {}
Ne21_5th_state = {}
Ne21_6th_state = {}
...
Ne21_29th_state = {}
Ne21_30th_state = {}

Can somebody help me automate this using python for loops?
Thanks in advance!

I want something like this:

for i in range(3, 11):
    states = f'Ar36_{i}th_state'
    print(states)

where the output would be:

Ar36_3th_state
Ar36_4th_state
Ar36_5th_state
Ar36_6th_state
Ar36_7th_state
Ar36_8th_state
Ar36_9th_state
Ar36_10th_state

but instead of printing it it would create individual dictionaries named Ar36_3th_state, Ar36_4th_state, Ar36_5th_state, ...

Upvotes: 0

Views: 107

Answers (3)

Marcel Suleiman
Marcel Suleiman

Reputation: 134

You can create "name" of pseudo variable and use it as key in dictionary like:

my_dic = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
my_empty_dic = {}

solution = {}

for i in range(1, 31):
    name = 'Ne21_'+str(i)+'st_state'

    #solution[name] = my_dic
    solution[name] = my_empty_dic

for pseudo_variable in solution:
    print(pseudo_variable, solution[pseudo_variable])

print(solution['Ne21_16st_state'])

for pseudo_variable in solution:
    if '_16st' in pseudo_variable:
        print(pseudo_variable, solution[pseudo_variable])

Upvotes: 0

Rajarshi Ghosh
Rajarshi Ghosh

Reputation: 462

can't we make a List of dictionaries

List of 30 (or any N) elements where each element is a dictionary with key = "Ar36_{i}th_state" and value = {whatever value you want}

Upvotes: 1

DyingInCS
DyingInCS

Reputation: 51

One way I've done this is using list comprehension.

key = list(
str(input(f"Please enter a Key for value {x + 1}: "))
if x == 0
else str(input(f"\nPlease enter a Key for value {x + 1}: "))
for x in range(3))

value = list(str(input(f"\nPlease enter a Bool for value {x + 1}: ")) 
for x in range(3))

BoolValues = dict(zip(key, value))

I first create a list of keys followed by a list of the values to be stored in the keys. Then I just zip them together into a dictionary. The conditional statements in the first list are only for a slightly better user-experience with \n being added if it's passed the first input.

Actually now that I look back on the question it may be slightly different to what I was thinking, are you trying to create new dictionaries for every matrix? If that is the case, is it something similar to this?: How do you create different variable names while in a loop?

Upvotes: 0

Related Questions