简体   繁体   中英

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

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)

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"],
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM