Python - Assign variable as one dictionary or another if something is true

Viewed 47

If I have two dictionaries, and I want to assign it to another variable based on an outside input, would there be a more Pythonic way of doing it.

dict_one = {"id": 1, "content": "content of the first dict"}

dict_two = {"id": 2, "content": "content of the second dict"}

dict_three = {"id": 3, "content": "content of the third dict"}

#insert many more dicts....

outside_input = 1

if outside_input == 1:
    result = dict_one
elif outside_input == 3:
    result = dict_three
3 Answers

Without having more details about your problem, i would probably use a nested dictionary, such as:

dict_of_dicts = {
        'dict_one': {"id": 1, "content": "content of the first dict"},
        'dict_two': {"id": 2, "content": "content of the second dict"}        
        }

outside_input = 'dict_one'

result = dict_of_dicts[outside_input]

Alternatively, if id inside the dicts just exists, for that reason, you can pull it outside as a key to reduce redundancy:

dict_of_dicts = {
        1: {"content": "content of the first dict"},
        2: {"content": "content of the second dict"}        
        }

or the third way, but slower when it comes to searching for a specific dictionary

list_of_dicts = [
        {"id": 1, "content": "content of the first dict"},
        {"id": 2, "content": "content of the second dict"}      
        ]
outside_input = 'dict_one'

result = [dict for dict in list_of_dicts.items() if dict['id'] == outside_input]

The last one is quiet inefficient and merely for academic reasons :D

I guess you could have another dictionary

allDict = {1:{"id": 1, "content": "content of the first dict"},2:{"id": 2, "content": "content of the second dict"},3:{"id": 3, "content": "content of the third dict"}}

out = 1
result = allDict.get(out)
dict_one = {"id": 1, "content": "content of the first dict"}

dict_two = {"id": 2, "content": "content of the second dict"}

dict_three = {"id": 3, "content": "content of the third dict"}

dicts = {1: dict_one, 2: dict_two, 3: dict_three}

outside_input = 1

result = dicts.get(outside_input)

Related