Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading