繁体   English   中英

从python中的嵌套字典打印唯一键

[英]Printing unique keys from nested dictionary in python

我有一个带有 2 个内部字典的字典dict_matches

dict_match的结构如下:

dict_match = {Query_ID:{Function_ID:{DB_ID:[func_ID]}}}

在键Query_ID ,我遍历这些并将它们与完全独立的 dict query_count_dict中的键进行比较,以确定键的重叠。

在这个循环中,我还导航到dict_matches中的基本字典,以查看主密钥与哪些密钥DB_ID '匹配'。 我的问题是,对应于顶级键Query_ID这个较低级别的键DB_ID可以重复(我只想查看唯一键)。 我尝试使用 set() 方法,但这实际上将字符串键拆分为其字符组件,并为每个较低级别的键打印唯一字符。 任何帮助表示赞赏!

见下面的代码

for k,v in dict_match.items():
    if k in query_count_dict.keys():
        print(k)
        detection_query.append(k)

        print(len(dict_match[k])/int(query_count_dict[k]))

    if type(v) is dict:
        recursive_items(v)

其中 recursive_items 是导航到基本字典的函数:

def recursive_items(dictionary):
    for k, v in dictionary.items():
        if type(v) is dict:
            recursive_items(v)
        else:
            print(set(k))

您可以通过在递归函数中传递键列表来打印所有唯一键,以便在导航到基时存储它们。 然后将其转换为设置以删除重复项。

def get_keys(dictionary, keys=[]):
    for k, v in dictionary.items():
        keys.append(k)
        if isinstance(v, dict):
            get_keys(v, keys)
    return set(keys)

dict_match = {'A': {'A': {'B': [0], 'H': [0]}, 'D': {'C': [0], 'A': [0]}},
              'B': {'C': {'A': [0]}, 'G': {'A': [0]}},
              'C': {'A': {'E': [0]}, 'B': {'F': [0], 'A': [0]}, 'C': {'B': [0]}}}

print(get_keys(dict_match))

它只会输出唯一的键:

{'G', 'B', 'E', 'F', 'C', 'H', 'A', 'D'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM