Python的多功能dict!
path-dict的Python项目详细描述
路径图
Python的多功能dict!在
安装
pip3 install path-dict
导入:
frompath_dictimportPathDict
使用
PathDict类似于普通的python dict,但是附带了一些方便的附加功能。在
初始化
^{pr2}$PathDict保留对原始初始化dict的引用:
user={"name":"Joe","age":22,"hobbies":["Playing football","Podcasts"]"friends":{"Sue":{"age":30},"Ben":{"age":35},}}joe=PathDict(user)>joe==user--->True>joe.dictisuser--->True
你也可以得到一个深拷贝:
joe=PathDict(user,deepcopy=True)>joe==user--->True>joe.dictisuser--->False
使用路径
获取和设置值可以使用键路径访问值:
joe=PathDict(user,deepcopy=True)# Get existing path>joe["friends","Sue","age"]--->30# Get non-existent, but valid path>joe["friends","Josef","age"]--->None# Set non-existent, but valid path, creates keysjoe["authentification","password"]="abc123">joe["authentification"]--->PathDict({"password":"abc123"})
使用无效路径获取或设置值将导致错误。例如,无效路径是试图访问int或list键的路径。所以,只使用路径来访问pathdict的层次结构。在
joe=PathDict(user,deepcopy=True)# Get invalid path (joe["hobbies"] is a list)>joe["hobbies","not_existent"]--->Error!
支持大多数dict方法
许多常用的dict方法都与PathDict一起工作:
pathdict=...forkey,valueinpathdict.items():...forkeyinpathdict:...forkeyinpathdict.keys():...forvalueinpathdict.values():...
在路径
处应用函数设置值时,可以使用lambda函数修改给定路径上的值。 函数应接受一个参数并返回修改后的值。在
stats_dict={}stats_pd=PathDict({})# Using a standard dict:if"views"notinstats_dict:stats_dict["views"]={}if"total"notinstats_dict["views"]:stats_dict["views"]["total"]=0stats_dict["views"]["total"]+=1# You can achieve the same using a PathDict:stats_pd["views","total"]=lambdax:(xor0)+1
过滤
PathDicts提供了一个过滤函数,它可以就地过滤给定路径上的列表或PathDict。在
要过滤一个列表,传递一个接受一个参数的函数(例如lambda ele: return ele > 10
),如果应该保留该值,则返回True,否则返回False。
要过滤PathDict,传递一个接受两个参数的函数(例如lambda key, value: key != "1"
),如果应该保留键值对,则返回True,否则返回False。在
可以对调用的PathDict筛选器进行筛选,也可以将路径传递到筛选器中,以便在给定路径上应用筛选器。在
还提供了一个filtered函数,它执行相同的操作,但是返回一个过滤的deepcopy,而不是就地过滤。在
joe=PathDict(user,deepcopy=True)# Remove all friends that are older than 33.joe.filter("friends",f=lambdak,v:v["age"]<33)>joe["friends"]--->PathDict({"Sue":{"age":30}})
聚集
聚合函数可以将PathDict组合到单个聚合值。
它接受一个init参数,一个带有三个参数的函数(例如lambda key, val, agg
)
joe=PathDict(user,deepcopy=True)# Remove all friends that are older than 33.friend_ages=joe.aggregate("friends",init=0,f=lambdak,v,a:a+v["age"])>friend_ages--->65
序列化为JSON
要序列化JSON的PathDict,请调用json.dumps(path_dict.dict)
。
如果尝试序列化PathDict对象本身,则操作将失败。在
- 项目
标签: