【问题标题】:how do I Unpack a nested dictionary and return a set with the nested values?如何解压嵌套字典并返回包含嵌套值的集合?
【发布时间】:2019-11-21 23:39:16
【问题描述】:
    spring =  {'April': {11,10,9,10,15,15,9,7,7,8,9,8,4,2,-1,-3,4,4,2,8,14,8,4,2,2,4,4,5,10,11,14}, 'May': {15,14,20,22,22,25,15,19,19,22,20,19,10,11,15,9,8,6,20,22,22,20,19,20,19,20,20,20,19,19,17}, 'June': {25,9,8,23,22,25,28,28,18,17,15,33,21,16,20,21,20,20,22,23,19,17,21,22,26,28,20,16,23,25}}

    summer = {'July':{26,27,24,25,25,27,28,26,28,23,20,22,34,25,8,9,17,22,23,25,20,26,23,14,24,27,28,23,25,23,20}, 'August':{8,9,15,25,20,21,24,18,22,25,25,24,26,37,20,20,23,23,27,19,17,22,26,29,24,22,24,28,24,25,23,23}, 'September': {21,26,18,21,27,28,32,23,22,20,29,17,10,11,13,14,17,16,7,9,8,9,13,18,20,20,21,24,23,17}}



    temp_data = {'spring': spring, 'summer': summer}


    for d in temp_data:
        print(d, temp_data[d])

当我解压它会产生结果

春季{'四月':{2、4、5、7、8、9、10、11、14、15、-3、-1},'五月':{6、8、9、10、 11, 14, 15, 17, 19, 20, 22, 25}, '六月': {33, 8, 9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 28}}

夏季{'七月':{34, 8, 9, 14, 17, 20, 22, 23, 24, 25, 26, 27, 28}, '八月': {37, 8, 9, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29},“九月”:{7, 8, 9, 10, 11, 13, 14, 16, 17, 18、20、21、22、23、24、26、27、28、29、32}}

^^^^^^ 这个结果保留了当月的数字,我需要做的是从几个月内获取数字并在季节内比较它们,看看每个月哪些数字相同,然后隔离这些数字。所以每个季节都应该返回那个季节常见的数字。

示例输出:

Temperatures in spring : {18, 19, 22, 23}
Temperatures in summer : {35, 36, 49, 18, 19, 22, 23}

所以,我的程序应该做的是遍历特定季节的月份并以集合表示法列出常用数字......现在超级卡住了。

【问题讨论】:

    标签: python-3.x dictionary nested set


    【解决方案1】:

    您可以使用 itertools 并为此设置方法:

    import itertools as it
    def foo(season):
        combos = list(it.combinations([month for month in season], 2))
        result = set()
        for x in combos:
            temp = (season[x[0]].intersection(season[x[1]]))
            result = result.union(temp)
        return result
    

    这个函数可以依次应用于每个字典:

    def extract(data):
        result = {}
        for x in data:
            temp = {x : foo(data[x])}   #pass each dict to foo function
            result.update(temp) 
            print(f"Temperatures in {x} : {temp[x]}")
        return result
    

    [编辑] 调用 extract(temp_data),它为 temp_data 中的每个 dict 调用一次 foo(data[x]),得到以下结果:

    Temperatures in spring : {8, 9, 10, 11, 14, 15, 17, 19, 20, 22, 25}
    Temperatures in summer : {8, 9, 14, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29} 
    

    该函数现在还返回此数据的新字典。

    【讨论】:

    • 代码运行到属性错误'dict' object has no attribute 'intersection' in line 6 where you set temp = ...
    • 如果您将temp_data 直接传递给foo,就会发生这种情况。我添加了一个调用函数以使其更清晰;只有个别的 dicts 应该被传递给 foo。为了更明确,foo 可以嵌套在extract 中。它现在应该可以工作了。
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 2021-08-10
    • 2011-05-13
    • 1970-01-01
    • 2013-11-30
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多