简体   繁体   English

如何在 Python 的 dict 中获取 dict 的路径?

[英]How do I can get path for dict in dict in Python?

There is dictionary which is generated by adding some data:有通过添加一些数据生成的字典:

some_dict = {'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}

I know that I can add there some data by using update method:我知道我可以使用 update 方法添加一些数据:

some_dict['dict1']['bar'].update({'some_key': value})

But what if a part of the code doesn't know correct way to update 'bar'?但是,如果部分代码不知道更新“栏”的正确方法怎么办? like:喜欢:

some_dict[???]['bar'].update({'some_key': value})

How can I update it correctly?我怎样才能正确更新它?

So I want to clarify your question.所以我想澄清你的问题。 The problem is that you have a dictionary within a dictionary and (ie overall_dict = {..., 'inner_dict': {'foo': 4 }} ) and what you want is for a function to update 'foo' without passing in overall_dict ?问题是您在字典中有一个字典(即overall_dict = {..., 'inner_dict': {'foo': 4 }} ),而您想要的是 function 更新 'foo' 而无需传入overall_dict Ie the function below即下面的function

def func1(dict): 
   dict['foo'] = 6

If that is the case, then there isn't too much of a problem.如果是这样的话,那么问题就不是太大了。 Python uses pointers and therefore if you pass func1(overall_dict['inner_dict']) then it will do what you want. Python 使用指针,因此如果你传递func1(overall_dict['inner_dict'])那么它会做你想做的事。 Essentially you can set a variable to point to the inner dictionary.本质上,您可以设置一个变量以指向内部字典。 When you update the new variable, then it will also update the overall_dict .当您更新新变量时,它也会更新overall_dict

I hope that helps.我希望这会有所帮助。 If you are wondering about other python dictionary questions, pythontutor.com如果您想知道其他 python 字典问题, pythontutor.com

My tests to make sure python is by pointers is here我的测试以确保 python 是指针在这里

This is also a really good textbook for python: link here这也是一本非常好的 python 教科书:链接在这里

Hope that helps.希望有帮助。

As far as I know, there is no standard Python function to do what you want.据我所知,没有标准的 Python function 可以做你想做的事。 You will need to implement some kind of search algorithm yourself.您将需要自己实现某种搜索算法。 Broadly speaking you will have the choice between a depth-first search or breadth-first search strategy.一般来说,您可以在深度优先搜索广度优先搜索策略之间进行选择。

A possible implementation of the former would be something along the lines of:前者的可能实现方式如下:

some_dict = {'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}

def get_nested_dict(d, name):
    stack = [d]
    while stack:
        for k, v in stack.pop().items():
            if k == name:
                return v

            if isinstance(v, dict):
                stack.append(v)


print(some_dict)
get_nested_dict(some_dict, 'bar')['new'] = 1
print(some_dict)

Producing:生产:

{'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}
{'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {'new': 1}}}

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

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