Nava
Nava

Reputation: 23

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:

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?

Upvotes: 2

Views: 227

Answers (2)

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

As far as I know, there is no standard Python function to do what you want. 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}}}

Upvotes: 1

gnahum
gnahum

Reputation: 436

So I want to clarify your question. The problem is that you have a dictionary within a dictionary and (i.e. overall_dict = {..., 'inner_dict' : {'foo': 4 }}) and what you want is for a function to update 'foo' without passing in overall_dict? I.e the function below

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. 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.

I hope that helps. If you are wondering about other python dictionary questions, pythontutor.com

My tests to make sure python is by pointers is here

This is also a really good textbook for python: link here

Hope that helps.

Upvotes: 1

Related Questions