具有自动和任意嵌套级别的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}$.

dictlists

#   nested dict of listsnd=nested_dict(2,list)nd["mouse"]["2"].append(12)nd["human"]["1"].append(12)

dictsets

#   nested dict of setsnd=nested_dict(2,set)nd["mouse"]["2"].add("a")nd["human"]["1"].add("b")

dictints

#   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}}

dictstrs

#   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支持dictdictsets等。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
返回数组无效的java方法   异步Java CompletableFuture获取其请求   java是否可以像RDBMS那样使用视图?   java如何在屏幕上只运行一个片段?   java无法从Vertex jdbc查询中获取结果   java从jtable获取对象的正确方法   java Spring 3数据设备替代方案   Java BigDecimal:四舍五入到客户首选的数字和增量   JAVA主窗口没有出现,我必须左键单击主窗口。java并单击run查看它   Eclipse RCP中的java进程自定义设备事件   JavaEclipse一次又一次地构建代码(没有任何更改)?   java如何实现对象合并