具有自动和任意嵌套级别的python字典
nested_dict的Python项目详细描述
nested_dict
nested_dict扩展defaultdict以支持具有多层嵌套性的pythondict:
替换dict
>>> fromnested_dictimportnested_dict>>> nd=nested_dict()>>> nd["one"]="1">>> nd[1]["two"]="1 / 2">>> nd["uno"][2]["three"]="1 / 2 / 3">>> ... forkeys_as_tuple,valueinnd.items_flat():... print("%-20s == %r"%(keys_as_tuple,value))...('one',) == '1' (1, 'two') == '1 / 2' ('uno', 2, 'three') == '1 / 2 / 3'
指定包含的类型
- If you want the nested dictionary to hold
- a collection (like the set in the first example) or
- a scalar with useful default values such as ^{tt6}$ or ^{tt7}$.
dict的lists
# nested dict of listsnd=nested_dict(2,list)nd["mouse"]["2"].append(12)nd["human"]["1"].append(12)
dict的sets
# nested dict of setsnd=nested_dict(2,set)nd["mouse"]["2"].add("a")nd["human"]["1"].add("b")
dict的ints
# nested dict of intsnd=nested_dict(2,int)nd["mouse"]["2"]+=4nd["human"]["1"]+=5nd["human"]["1"]+=6nd.to_dict()#{'human': {'1': 11}, 'mouse': {'2': 4}}
dict的strs
# nested dict of stringsnd=nested_dict(2,str)nd["mouse"]["2"]+="a"*4nd["human"]["1"]+="b"*5nd["human"]["1"]+="c"*6nd.to_dict()#{'human': {'1': 'bbbbbcccccc'}, 'mouse': {'2': 'aaaa'}}
迭代nested_dict
在深度或不均匀嵌套的字典中迭代是一种不需要递归的痛苦。 nested dict允许您在迭代之前将嵌套的级别展平到tuples中。
您不需要事先知道有多少级别的嵌套:
fromnested_dictimportnested_dictnd=nested_dict()nd["one"]="1"nd[1]["two"]="1 / 2"nd["uno"][2]["three"]="1 / 2 / 3"forkeys_as_tuple,valueinnd.items_flat():print("%-20s == %r"%(keys_as_tuple,value))# (1, 'two') == '1 / 2'# ('one',) == '1'# ('uno', 2, 'three') == '1 / 2 / 3'
- 嵌套指令提供
- items_flat()
- keys_flat()
- values_flat()
(iteritems_flat()、iterkeys_flat()和itervalues_flat()是python 2.7风格的同义词。)
转换到/从词典
nested_dict的魔力有时会妨碍(例如,pickleing)。
- 我们可以使用
- nested_dict.to_dict()
- nested_dict constructor
>>> fromnested_dictimportnested_dict>>> nd=nested_dict()>>> nd["one"]=1>>> nd[1]["two"]="1 / 2" # # convert nested_dict -> dict and pickle # >>> nd.to_dict(){1: {'two': '1 / 2'}, 'one': 1} >>> importpickle>>> binary_representation=pickle.dumps(nd.to_dict()) # # convert dict -> nested_dict # >>> normal_dict=pickle.loads(binary_representation)>>> new_nd=nested_dict(normal_dict)>>> nd==new_ndTrue
defaultdict
nested_dict扩展collections.defaultdict
您可以使用defaultdict获得任意嵌套的“自动激活”词典。
fromcollectionsimportdefaultdictnested_dict=lambda:defaultdict(nested_dict)nd=nested_dict()nd[1][2]["three"][4]=5nd["one"]["two"]["three"][4]=5
但是,只有nested_dict支持dict的dict的sets等。