在Python中存储字典路径 [英] Storing dictionary path in Python
问题描述
python的新手,假设我有一个字典:
Brand new to python, Let's say I have a dict:
kidshair = {'allkids':{'child1':{'hair':'blonde'},
'child2':{'hair':'black'},
'child3':{'hair':'red'},
'child4':{'hair':'brown'}}}
如果child3定期更改其头发颜色,我可能想编写一个应用程序以加快数据维护速度.在此示例中,我将使用:
If child3 changes their hair colour regularly, I might want to write an application to speed up the data maintenance. In this example i'd use:
kidshair['allkids']['child3']['hair'] = ...
是否有任何方法可以将此路径存储为变量,以便我可以随意访问它?显然
Is there any way to store this path as a variable so I can access it at my leasure? Obviously
mypath = kidshair['allkids']['child3']['hair']
导致mypath ='red'.有没有办法对路径本身进行硬编码,所以我可以使用:
results in mypath = 'red'. Is there any possible way to hard code the path itself so I could use:
mypath = 'blue'
代表
kidshair['allkids']['child3']['hair'] = 'blue'
谢谢,ATfPT
推荐答案
根据您的需要,最简单的选择可能是使用元组作为字典键而不是嵌套词典:
Depending on what you need, the easiest option may be to use tuples as dictionary keys instead of nested dictionaries:
kidshair['allkids', 'child3', 'hair']
mypath = ('allkids', 'child3', 'hair')
kidshair[mypath]
唯一的问题是您无法获得字典的一部分,因此,例如,您无法(轻松/高效)访问与'child3'
相关的所有内容.根据您的使用情况,这可能是不合适的解决方案.
The only issue with this is that you can't get a portion of the dictionary, so, for example, you can't (easily/efficiently) access everything to do with 'child3'
. This may or may not be an appropriate solution for you depending on your usage.
当前结构的另一种选择是执行以下操作:
An alternative with your current structure is to do something like this:
>>> from functools import partial
>>> test = {"a": {"b": {"c": 1}}}
>>> def itemsetter(item):
... def f(name, value):
... item[name] = value
... return f
...
>>> mypath = partial(itemsetter(test["a"]["b"]), "c")
>>> mypath(2)
>>> test
{'a': {'b': {'c': 2}}}
在这里,我们创建一个函数 itemsetter()
,该函数(与 operator.itemgetter()
)给我们提供了一个功能,该功能可以在给定字典中设置相关键.然后,我们使用 functools.partial
生成该功能的版本,其中包含我们要预填的键.也不是 mypath = blue
,但这还不错.
Here we make a function itemsetter()
, which (in the vein of operator.itemgetter()
) gives us a function that that sets the relevant key in the given dictionary. We then use functools.partial
to generate a version of this function with the key we want pre-filled. It's not quite mypath = blue
either, but it's not bad.
如果您不想为使与 operator
模块保持一致的内容而烦恼,只需执行以下操作:
If you don't want to bother with making something consistent to the operator
module, you could simply do:
def dictsetter(item, name):
def f(value):
item[name] = value
return f
mypath = dictsetter(test["a"]["b"], "c")
mypath(2)
这篇关于在Python中存储字典路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!