Home > Back-end >  Creating a nested dictionary with a for loop in Python
Creating a nested dictionary with a for loop in Python

Time:10-15

I am trying to get the Expected Output below where it makes subfolders named John1, John2, John3 below and then it adds {0: 'John', 1: 'John', 2: 'John', 3: 'John'} values to each essentially creating a nested dictionary. How would I be able to do that and get the Expected Output?

dicts = {}
keys = range(4)
name_vals = ['John' str(k 1) for k in range(3)]
values = ["Hi", "I", "am", "John"]
for k in name_vals:
    for i in keys:
        for x in values:
            dicts[k][i] = x

Expected Output:

{John1: {0: 'John', 1: 'John', 2: 'John', 3: 'John'},
 John2: {0: 'John', 1: 'John', 2: 'John', 3: 'John'},
 John3: {0: 'John', 1: 'John', 2: 'John', 3: 'John'}}

CodePudding user response:

this is the way with list comprehension

values = ["Hi", "I", "am", "John"]

{ f'Jhon{k 1}': {i: values[3] for i in range(len(values))} for k in range(3)}

Output:

{'Jhon1': {0: 'John', 1: 'John', 2: 'John', 3: 'John'},
 'Jhon2': {0: 'John', 1: 'John', 2: 'John', 3: 'John'},
 'Jhon3': {0: 'John', 1: 'John', 2: 'John', 3: 'John'}}

CodePudding user response:

you can try this

keys = range(4)
name_vals = ['John' str(k 1) for k in range(3)]
values = ["Hi", "I", "am", "John"]
    
dicts = {}
for k in name_vals:
    subdict = {}
    for i in keys:
        subdict[i] = values[i]
    dicts[k] = subdict
            
dicts

output

{'John1': {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'},
 'John2': {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'},
 'John3': {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}}

if u want all values to be 'john' then just replace values[i] with values[3]

  • Related