Home > Net >  How to create a multidimensional dictionary in Python with the below expected output?
How to create a multidimensional dictionary in Python with the below expected output?

Time:07-24

I'm trying to create a multidimensional dictionary in the below-mentioned expected output format and when I run the code below

# existing dictionary  
models = {'sss':{'a':1, 'b':2}, 'xxx':{'c':3, 'd':4}}
    
   # using keys 'sss' from the models dictionary to iterate
    for m in models:
        
        s_data = {m: {}}
        
        specs = ['apple', 'cat', 'tomato']
        
        for spec in specs:
            
            if 'apple' in spec:
                s_data[m]['fruit'] = spec
                
            if 'cat' in spec:
                s_data[m]['animal'] = spec
            
            if 'tomato' in spec:
                s_data[m]['vegetable'] = spec
    
    print(s_data)
            

expected output (a dictionary in the below format):

 {'sss': {'fruit': 'apple', 'animal':'cat', 'vegetable': 'tomato'},
        'xxx': {'fruit': 'apple', 'animal':'cat', 'vegetable': 'tomato'}}

CodePudding user response:

The problem is that you're redefining s_data at each iteration of the loop, meaning you only get the data from the last iteration. You should define it once before the for loop:

models = {'sss':{'a':1, 'b':2}, 'xxx':{'c':3, 'd':4}}
    
# using keys 'sss' from the models dictionary to iterate
s_data = {m:{} for m in models}
specs = ['apple', 'cat', 'tomato']
for m in models:
    
    for spec in specs:
        
        if 'apple' in spec:
            s_data[m]['fruit'] = spec
            
        if 'cat' in spec:
            s_data[m]['animal'] = spec
        
        if 'tomato' in spec:
            s_data[m]['vegetable'] = spec

print(s_data)

Output:

{'sss': {'fruit': 'apple', 'animal': 'cat', 'vegetable': 'tomato'},
'xxx': {'fruit': 'apple', 'animal': 'cat', 'vegetable': 'tomato'}}

CodePudding user response:

Another solution:

models = {"sss": {"a": 1, "b": 2}, "xxx": {"c": 3, "d": 4}}

a, b = ("apple", "cat", "tomato"), ("fruit", "animal", "vegetable")

out = {key: dict(zip(b, a)) for key in models}
print(out)

Prints:

{
    "sss": {"fruit": "apple", "animal": "cat", "vegetable": "tomato"},
    "xxx": {"fruit": "apple", "animal": "cat", "vegetable": "tomato"},
}
  • Related