0

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)
2
  • 1
    do you really want sets as the values to your keys? Commented Nov 17, 2022 at 10:49
  • 1
    This output is not valid. There's no set {'a', 'l', 'a', 'l'} Commented Nov 17, 2022 at 10:50

2 Answers 2

2

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"],
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also, a dict with int keys like this is moot, a list does the same thing with less space.
@timgeb Yes, lists of lists would be better case for this.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.