Python—如果某个值为true,则将变量指定为一个字典或另一个字典
如果我有两个字典,并且我想根据外部输入将它分配给另一个变量,那么会有一种更类似python的方法吗Python—如果某个值为true,则将变量指定为一个字典或另一个字典,python,dictionary,variable-assignment,Python,Dictionary,Variable Assignment,如果我有两个字典,并且我想根据外部输入将它分配给另一个变量,那么会有一种更类似python的方法吗 dict_one = {"id": 1, "content": "content of the first dict"} dict_two = {"id": 2, "content": "content of the second dict"} dict_three = {&
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
如果没有关于您的问题的更多详细信息,我可能会使用嵌套字典,例如:
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]
或者,如果DICT中的id只是存在的,出于这个原因,您可以将其作为键拉到外部以减少冗余:
dict_of_dicts = {
1: {"content": "content of the first dict"},
2: {"content": "content of the second dict"}
}
或者第三种方法,但在搜索特定词典时速度较慢
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]
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)
最后一本字典效率很低,只是出于学术原因:我想你可以再买一本字典
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]
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)