Home > Net >  Create a dictionary with input in python
Create a dictionary with input in python

Time:04-13

I'm trying to create a dictionary from user input, with the ability to add nested dictionaries as well. The code I have now can create a dictionary, with one level nesting, but I think there's a better way to do this and also make the nesting levels be unlimited, does anyone know how to achieve this?

def input_to_dict():
    def str_or_list(value):
        # return list if values are separated by comma, else return string
        if "," in value:
            value = value.split(",")
            value = [i.strip() for i in value]
            return value
        else:
            return value.strip()
    
    temp_dict = {}
    while True:
        key = input('Key: ').title()
        if not key:
            break
        value = input('Value: ')
        # if value is key-value pair, nest dict
        if ":" in value:
            value = value.split(":")
            value_k = value[0].strip().title()
            value_v = value[1].strip()
            temp_dict[key] = {value_k: str_or_list(value_v)}
            
        else:
            temp_dict[key] = str_or_list(value)
        
    return temp_dict

CodePudding user response:

If you want the nested dictionaries to be able to include arbitrary entries, including more nested dictionaries, you probably want a recursive function, e.g.:

def input_to_dict():
    d = {}
    while True:
        k = input('Key: ').title()
        if not k:
            break
        v = input('Value: ')
        if v == ":":
            d[k] = input_to_dict()
        elif "," in v:
            d[k] = [i.strip() for i in v]
        else:
            d[k] = v
    return d
Key: foo
Value: bar
Key: moar
Value: :
Key: foo
Value: bar
Key: moar
Value: :
Key: foo
Value: bar
Key:
Key:
Key:
{'Foo': 'bar', 'Moar': {'Foo': 'bar', 'Moar': {'Foo': 'bar'}}}

CodePudding user response:

This is the code I ended up using thanks to @Samwise answer

  • Related