Search code examples
pythonpython-3.xgraph

I want to create a dict like this from input in python


all the contents must be inserted from the input

graph={
'A':{'B':3,'C':4},
'B':{'A':3,'C':5},
'C':{'B':5,'D':'1'},
'D':{'C':1},
}

Solution

  • def make_dict():
        d = {}
        while True:
            key = input("Enter the key of dict or stay blank to finish adding key to this level of dict: ")
            if key == "":  # just stay blank to out from func
                break
            ch = input(f"Do you wanna to create nested dict for the key{key}? [y / <Press Enter for No>] ")
            if ch == "y":
                value = make_dict()  # use recursion
            else:
                value = input(f"Enter the value for the key {key}: ")
            d[key] = value
        return d
    
    
    print(make_dict())
    

    link to screenshot