Home > Net >  How to create a nested dictionary from a string list (Python)?
How to create a nested dictionary from a string list (Python)?

Time:11-17

I'm trying to create a nested dictionary from a list of strings. Each index of the strings corresponds to a key, while each character a value.

I have a list:

list = ['game', 'club', 'party', 'play']

I would like to create a (nested) dictionary:

dict = {0: {'g', 'c', 'p', 'p'}, 1: {'a', 'l', 'a', 'l'}, 2: {'m', 'u', 'r', 'a'}, etc.}

I was thinking something along the lines of:

res = {} 
for item in range(len(list)):    
    for i in list[item]:   
        if i not in res:   
            # create a key (index - ex. '0') and a value (character - ex. 'g' of 'game')  
        else: 
            # put the value in the corresponding key (ex. 'c' of 'club')
print(res)

CodePudding user response:

Note: you cannot have sets with duplicate values. Instead, create a dictinary where values are lists or tuples:

from itertools import zip_longest

lst = ["game", "club", "party", "play"]

out = {
    i: [v for v in t if not v is None] for i, t in enumerate(zip_longest(*lst))
}

print(out)

Prints:

{
    0: ["g", "c", "p", "p"],
    1: ["a", "l", "a", "l"],
    2: ["m", "u", "r", "a"],
    3: ["e", "b", "t", "y"],
    4: ["y"],
}

CodePudding user response:

Andrejs solution is surely the more elegant one. But to stay closer to your proposed solution you could do something like this:

items = ['game', 'club', 'party', 'play']
result = {}
for item in items:
    for (idx, char) in enumerate(list(item)):
        if idx not in result:
            result[idx] = [char]
        else:
            result[idx].append(char)
print(result)
  • Related