【问题标题】:Python nested dictionary comprehension returns empty dictionariesPython 嵌套字典理解返回空字典
【发布时间】:2013-11-30 19:23:55
【问题描述】:

我正在使用字典理解来提取嵌套值。我有以下代码(作为示例):

d = {1: 'a', 2: 'b', 3: 'c'}
e = {4: 'd', 5: 'e', 6: 'f'}
f = {7: 'g', 8: 'h', 9: 'i'}

# stick them together into another dict
data_dict = {'one': d, 'two': e, 'three': f}
#say we're looking for the key 8

output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()}
output = {'one': {}, 'three': {8: 'h'}, 'two': {}}

我需要做什么才能获得“三”及其价值?我不想返回空匹配项。

谢谢

【问题讨论】:

    标签: python dictionary list-comprehension


    【解决方案1】:

    类似这样的:

    >>> {k: {8: v[8]} for k, v in data_dict.items() if 8 in v}
    {'three': {8: 'h'}}
    

    【讨论】:

    • 所以如果我没看错的话,它是在第一级按键拉出嵌套字典?
    • @shelbydz 它与您的代码相同,但无需遍历整个 dict 来检查密钥,只需使用 in 运算符。这是一个针对字典的O(1) 操作。
    【解决方案2】:

    对 162+ 行的理解太大了。这是传统的方式:

    #!/usr/local/cpython-3.3/bin/python
    
    import pprint
    
    d = {1: 'a', 2: 'b', 3: 'c'}
    e = {4: 'd', 5: 'e', 6: 'f'}
    f = {7: 'g', 8: 'h', 9: 'i'}
    
    # stick them together into another dict
    data_dict = {'one': d, 'two': e, 'three': f}
    #say we're looking for the key 8
    
    def just_8(dict_):
        outer_result = {}
        for outer_key, inner_dict in dict_.items():
            inner_result = {}
            if 8 in inner_dict:
                inner_result[8] = inner_dict[8]
            if inner_result:
                outer_result[outer_key] = inner_result
        return outer_result
    
    output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()}
    pprint.pprint(output)
    
    output_just_8 = just_8(data_dict)
    pprint.pprint(output_just_8)
    

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 2013-07-28
      • 2011-06-06
      • 2016-11-25
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多