【问题标题】:How to create a nested dictionary from a string list (Python)?如何从字符串列表(Python)创建嵌套字典?
【发布时间】:2022-11-17 18:49:24
【问题描述】:

我正在尝试从字符串列表创建嵌套字典。 字符串的每个索引对应一个键,而每个字符对应一个值。

我有一个清单:

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

我想创建一个(嵌套的)字典:

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

我在想一些事情:

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)

【问题讨论】:

  • 你真的想要 sets 作为你的键值吗?

标签: python string list dictionary


【解决方案1】:

注意:您不能拥有具有重复值的集合。相反,创建一个字典,其中值是列表或元组:

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)

印刷:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多