【问题标题】:Add a value list for specific keys in dictionary (python 3.x)为字典中的特定键添加值列表(python 3.x)
【发布时间】:2021-12-29 07:57:28
【问题描述】:

我想返回一个字典,其中大写字母作为键,列表小写字母作为值。

def sample(d):
    new_group = {}
    for small_letters, capitals in d.items():
        for capital in capitals:            
            new_group[capital] = [small_letters]
    return(new_group)

print(sample({"aaa":["A","B"], "bbb":["A","C"], "ccc":["A"]}))

我的代码返回:

{"A":["ccc"], "B":["aaa"], "C":["bbb"]}

预期结果:

{"A":["aaa","bbb","ccc"], "B":["aaa"], "C":["bbb"]}

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    您正在重写字典值,而不是附加到列表中。

    def sample(d):
        new_group = {}
        for small_letters, capitals in d.items():
            for capital in capitals:            
                new_group[capital] = new_group.get(capital, []) + [small_letters]
        return(new_group)
    
    print(sample({"aaa":["A","B"], "bbb":["A","C"], "ccc":["A"]}))
    

    结果:

    {'A': ['aaa', 'bbb', 'ccc'], 'B': ['aaa'], 'C': ['bbb']}
    

    【讨论】:

    • 谢谢拉里,这是我的大问题,我的代码没有将元素添加到列表中,而是覆盖了现有元素。这是get()方法的使用。再次感谢,这让我头疼了几个小时。
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2021-02-08
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多