【问题标题】:Python create key for top level and nested dictionary at the same timePython同时为顶级字典和嵌套字典创建键
【发布时间】:2021-06-07 08:45:10
【问题描述】:

我有一个字典,其中包含其值是字典的键。我将如何同时为顶级字典和嵌套字典创建一个键。类似于以下内容:

famCountDictofDicts = {"one": {"oneA": 1, "oneB": 2, "oneC": 3}, "two": {"twoA": 1, "twoB": 2, "twoC": 3}}

famCountDictofDicts 
{'one': {'oneA': 1, 'oneB': 2, 'oneC': 3},
 'two': {'twoA': 1, 'twoB': 2, 'twoC': 3}}

famCountDictofDicts["three"]["threeA"] = 1

famCountDictofDicts
{'one': {'oneA': 1, 'oneB': 2, 'oneC': 3},
 'two': {'twoA': 1, 'twoB': 2, 'twoC': 3},
 'three': {'threeA': 1}}

由于这不起作用,我想我可以创建一个空键然后填充它,但我也不确定如何做到这一点。

我想这样做,因为我有一个数据帧的文件列表,并且对于每个数据帧,我需要存储某些变量的值,但并非所有数据帧都具有相同的变量

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您可以通过将您的字典声明为defaultdictdicts 来做到这一点。像这样:

    from collections import defaultdict
    
    
    famCountDictofDicts = {"one": {"oneA": 1, "oneB": 2, "oneC": 3}, "two": {"twoA": 1, "twoB": 2, "twoC": 3}}
    
    famCountDictofDicts = defaultdict(dict, famCountDictofDicts)    
    famCountDictofDicts["three"]["threeA"] = 1  # <- this now works
    

    更多信息,请参阅documentation

    【讨论】:

    • 这非常有效。谢谢你!我只是打电话给famCountDictofDicts = defaultdict(dict) 而不是famCountDictofDicts = defaultdict(dict, famCountDictofDicts),因为我没有预定义的键和值。
    【解决方案2】:

    为了实现您在代码示例中显示的目标,您可以在赋值右侧创建嵌套字典,如下所示:

        famCountDictofDicts["three"] = {"threeA": 1}
    

    【讨论】:

    • 我试过了,但随后的每个调用都不会附加最后一个调用:famCountDictofDicts["three"] = {"threeB": 1} 只会导致{'one': {'oneA': 1, 'oneB': 2, 'oneC': 3}, 'two': {'twoA': 1, 'twoB': 2, 'twoC': 3}, 'three': {'threeB': 1}}
    猜你喜欢
    • 2023-01-18
    • 1970-01-01
    • 2021-05-17
    • 2014-03-30
    • 2021-11-29
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多