简体   繁体   English

Python创建多层动态字典

[英]Python Create Multi-layer Dynamic Dictionary

I want to create a 3 layer dictionary. 我想创建一个三层字典。 All keys and values are strings and only their presence in the dictionary is important (I want to remove repetition and order is not important). 所有键和值都是字符串,只有它们在字典中的存在很重要(我要删除重复项,顺序并不重要)。 So this is the function I wrote: 这就是我写的函数:

def UpdateDic3(key1,key2,key3,val,dic):
  if not key1 in dic.keys():
    dic[key1][key2][key3] = {val}
  elif not key2 in dic[key1].keys():
      dic[key1][key2][key3] = {val}
  elif not key3 in dic[key1][key2].keys():
      dic[key1][key2][key3] = {val}
  else:
      dic[key1][key2][key3].add(val)
  return dic

and searching for multilayer dictionary I found this: 并搜索多层字典,我发现了这一点:

l=lambda:defaultdict(l)
src_tree =l()

src_tree = UpdateDic3(k1,k2,k3,value,src_tree)

Isn't there a better way to make a 3 layer dictionary than the l=lambda:defaultdict(l) ? 有没有比l=lambda:defaultdict(l)更好的制作3层字典的方法了?

I need a tree structure, with access to every layer's keys. 我需要一个树结构,可以访问每个层的键。

Just use a set filled with tuples. 只需使用充满元组的集合即可。

src_tree = set()
str_tree.add((k1, k2, k3))
def multiple_dictionary(k, v): 
    if len(k) > 1: 
        v = multiple_dictionary(k[1:], v) 
    return {k[0]: v}

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

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