【问题标题】:Pythonic way to find the key associated with nested dictionary查找与嵌套字典关联的键的 Pythonic 方法
【发布时间】:2017-06-19 07:17:20
【问题描述】:

我有一个字典,其中每个键都有一个字典作为其值(嵌套字典都有相同的键集)。我试图找到与子键上的两个条件相关联的键:给定另一个子键的子键的最大值为 True。

例如:

d = {'key1' : {'subkey1' : True,  'subkey2' : 4},
     'key2' : {'subkey1' : True,  'subkey2' : 8},
     'key3' : {'subkey1' : False, 'subkey2' : 1},
     'key4' : {'subkey1' : False, 'subkey2' : 9} }

我希望结果为“key2”,因为它是“subkey2”的最大值,其中“subkey1”为真。

我的想法是将所有内容放入一个数组中并找到与这些值相关联的索引,但我的印象是无需添加更多变量来存储相同的信息即可完成此操作。我认为可能有更好的方法,因为我对 Python 比较陌生。

有什么建议吗?谢谢!

【问题讨论】:

  • 您必须进行全面扫描,将事物分组到一个新的字典映射子键到一个列表中,该列表包含来自d 的键和subkey2 值。这不会有效率。你是怎么得到这个结构的?
  • 将 dict 转换为 subkey1 为 true 的 dicts 列表,然后使用带有 key 函数的 max 函数

标签: python python-3.x dictionary


【解决方案1】:

这是您问题的可选实现。

首先,用 True 过滤所有 subkey1。

其次,从过滤后的字典中找到subkey2中的最大值。

d = {'key1' : {'subkey1' : True,  'subkey2' : 4},
     'key2' : {'subkey1' : True,  'subkey2' : 8},
     'key3' : {'subkey1' : False, 'subkey2' : 1},
     'key4' : {'subkey1' : False, 'subkey2' : 9} }

max_d = {v["subkey2"]:{k:v} for k,v in d.items() if v["subkey1"]} # create new dictionary that the key is the value from subkey2 and the value is the original key and value.
max_int = max(max_d.keys(), key=int) # get the max key

print (max_d[max_int]) # print the maximum 

>>> {'key2': {'subkey1': True, 'subkey2': 8}}

【讨论】:

  • 谢谢!这很奏效,我学到了一些关于创建字典和使用 max() 的新知识。
【解决方案2】:

这有点令人费解,但如何:

print(d[max({key:d[key] for key in [k for k in d.keys() if d[k]['subkey1'] is True]})])

首先我们创建一个子键为 True 的主键列表,然后为每个主键重建一个键值对字典,并获取具有最大值的键

尚未对此进行全面测试,因此如果您认为值得花时间,请在最后进行。

【讨论】:

    【解决方案3】:

    您可能需要的是来自functoolsreduce

    这是您可能正在寻找的解决方案:

    from functools import reduce
    import operator
    
    d = {'key1' : {'subkey1' : True,  'subkey2' : 4},
         'key2' : {'subkey1' : True,  'subkey2' : 8},
         'key3' : {'subkey1' : False, 'subkey2' : 1},
         'key4' : {'subkey1' : False, 'subkey2' : 9} }
    maxsum=0
    for k in d:
        if reduce(operator.getitem, [k,'subkey1'], d):
            value = (reduce(operator.getitem, [k,'subkey2'], d))
            if maxsum<value:
                maxsum=value
    print(maxsum)
    

    基本上这个reduce(operator.getitem, [k,'subkey1'], d) 的作用是从子字典中获取值。例如:

    d = {'John' : {'Male' : True,  'age' : 41}}
    reduce(operator.getitem, ['John','Male'], d)
    

    输出:

    True
    

    这里reduce遍历John-->Male,得到结果为True

    我们也可以将列表作为参数。看看这个,

    from functools import reduce
    import operator
    
    d = {'John' : {'Male' : True,  'age' : 41},
             'Vishnu':{'Male':True ,'age':23}}
    chklist1 = ['John','Male']
    chklist2 = ['Vishnu','age']
    print(reduce(operator.getitem, chklist1, d))
    print(reduce(operator.getitem, chklist2, d))
    

    输出:

    True
    23
    

    你不能总是期望 dict 是 dict 的 dict。可以说一个字典的一个字典的字典。 (谁知道呢?事情发生了!)

    from functools import reduce
    import operator
    
    d = {
        "John":{
            "Age": 23,
            "Sex": 'M',
            "Country": 'USA'
            },
        "Vishnu":{
            "Age": 1,
            "Country": {
                "India": 'TamilNadu',
                "USA": None,
                "South Africa": None
            }
            }
    }
    chklist1 = ['John','Age']
    chklist2 = ['Vishnu','Country','India']
    print(reduce(operator.getitem, chklist1, d))
    print(reduce(operator.getitem, chklist2, d))
    

    输出:

    23
    TamilNadu
    

    所以现在回到你的问题:

    for k in d:
        if reduce(operator.getitem, [k,'subkey1'], d):
            value = (reduce(operator.getitem, [k,'subkey2'], d))
            if maxsum<value:
                maxsum=value
    print(maxsum)
    

    对于每个键 k 这将是您的 key1,key2,... 等等。首先reduce(operator.getitem, [k,'subkey1'], d) 检查其中包含的值是True 还是False。仅当它是 True 时才进行

    然后将maxsum设置为dict的sub_dict中的第二项。对于每个键,都会检查它,如果发现另一个大于当前值的值,则更改该值,否则继续。直到找到可以打印的最大值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多