【问题标题】:Python How to Extract data from Nested DictPython如何从嵌套字典中提取数据
【发布时间】:2018-04-20 11:19:16
【问题描述】:

我有 python networkX 代码的输出:

flow_value, flow_dict = nx.maximum_flow(T, 'O', 'T')

print(flow_dict)

#Output as followesenter

#{'O': {'A': 4, 'B': 6, 'C': 4}, 'A': {'B': 1, 'D': 3}, 'B': {'C': 0, 'E': 3,'D': 4}, 'C': {'E': 4}, 'E': {'D': 1, 'T': 6}, 'D': {'T': 8}, 'T': {}}

我要提取的表格中的所有数据如下:

#('O','A',4),('O','B','6'),('O','C','4'),('A','B',1),......,('D','T',8)

我有什么方法可以遍历嵌套的 dict 并获取我需要的数据?

【问题讨论】:

  • 是的,你试过什么?您是否查看过“如何在 Python 中迭代字典”?
  • [(key, subkey, value) for key, subdict in flow_dict.items() for subkey, value in subdict.items()]
  • 彼得成功了!!!

标签: python python-3.x dictionary nested networkx


【解决方案1】:

我试过了,效果很好。一些类型检查只捕获字符串

def retrieve_all_strings_from_dict(nested_dict, keys_to_ignore = None):

    values = []

    if not keys_to_ignore:
        keys_to_ignore = []
    else: keys_to_ignore = to_list(keys_to_ignore)    

    if not isinstance(nested_dict,dict):
        return values

    dict_stack = []
    dict_stack.append(nested_dict)

    for dict_var in dict_stack:        
        data_list = [v for k,v in dict_var.items() if all([isinstance(v,str), k not in keys_to_ignore]) ]        
        additional_dicts = [v for k,v in dict_var.items() if isinstance(v,dict)]                    

        for x in additional_dicts:
            dict_stack.append(x)

        for w in data_list:
            values.append(w) 

    return values           

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 2021-02-12
    • 1970-01-01
    • 2021-06-02
    • 2021-10-29
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多