Search code examples
pythonpython-3.xdictionaryif-statementredundancy

Produce any number of if statements and dictionary indexes


I have a problem. How do I execute a number of if statements but also change the amount of dictionary indexes as well? I think my code sums it up pretty well what I want to happen, but I'll explain further. with dict = {"Hi":{"Hello":{"Greetings":"Goodbye"}}} I want a set of if statements to be able to access every point in this dictionary without having to type each one individually. So for this one,

If level == 1:
    print(dict["Hi"])
If level == 2:
    print(dict["Hi"]["Hello"])
If level == 3:
    print(dict["Hi"]["Hello"]["Greetings"])

An example piece of code:

E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}}


def PATH_APPEND(path, item, location, content):
    if len(location) == 1:
        E[location[0]] = item
        E[location[0]][item] = content
    if len(location) == 2:
        E[location[0]][location[1]] = item
        E[location[0]][location[1]][item] = content
    if len(location) == 3:
        E[location[0]][location[1]][location[2]][item] = content
    # ... and so on

PATH_APPEND(E, "Hi.txt", ["C:","Desktop.fld"], "Hi There, World")
print(E)
#{"C:":{"Desktop.fld":{ ... , "Hi.txt":{"Content":"Hi There, World"}}}}

I got an error while running my example, but I think it gets the point across fine.


Solution

  • You don't need any if statements for this task, you can use a simple for loop to descend into your nested dictionary.

    from pprint import pprint
    
    def path_append(path, item, location, content):
        for k in location:
            path = path[k]
        path[item] = {"Content": content}
    
    # test
    
    E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}}    
    print('old')
    pprint(E)
    
    path_append(E, "Hi.txt", ["C:", "Desktop.fld"], "Hi There, World")
    print('\nnew')
    pprint(E)
    

    output

    old
    {'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}}}}
    
    new
    {'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'},
                            'Hi.txt': {'Content': 'Hi There, World'}}}}
    

    BTW, you shouldn't use dict as a variable name because that shadows the built-in dict type.

    Also, it's conventional in Python to use lower-case for normal variable and function names. All uppercase is used for constants, and capitalized names are used for classes. Please see the PEP 8 -- Style Guide for Python Code for further details.

    I also noticed that the code block at the start of your question uses If instead of the correct if syntax, but perhaps that's supposed to be pseudo-code.