【问题标题】:Python - Assign variable as one dictionary or another if something is truePython - 如果某事为真,则将变量分配为一个字典或另一个字典
【发布时间】:2021-05-11 18:19:31
【问题描述】:

如果我有两个字典,并且我想根据外部输入将其分配给另一个变量,是否有更 Pythonic 的方式来做呢?

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

【问题讨论】:

    标签: python dictionary variable-assignment


    【解决方案1】:

    如果没有关于您的问题的更多详细信息,我可能会使用嵌套字典,例如:

    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]
    

    或者,如果 dicts 中的 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]
    

    最后一个效率低下,仅出于学术原因:D

    【讨论】:

      【解决方案2】:

      我猜你可以有另一本字典

      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)
      

      【讨论】:

        【解决方案3】:
        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)
        
        

        【讨论】:

          猜你喜欢
          • 2021-09-03
          • 1970-01-01
          • 2014-03-26
          • 2020-12-07
          • 2022-11-22
          • 1970-01-01
          • 2017-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多