【问题标题】:How to return a new dictionary obtained by updating a 2 level dictionary?如何返回通过更新 2 级字典获得的新字典?
【发布时间】:2019-06-15 01:47:17
【问题描述】:

我需要编写一个函数,该函数返回通过更新两级字典(dict2)获得的字典。结果字典 (newdict2) 包含 newdict2[key1][key2] == value。我不确定我的 for 循环和 if 语句是否设置正确或如何更新需要返回的值。

我一直在尝试一些嵌套的 for 循环和 if 语句无济于事。当我尝试插入测试示例时,出现名称错误。我会在下面发帖。尽管如此,我仍然不确定我的代码能否正常工作。我在运行测试用例时收到名称类型错误,提示未定义 DD。

我的功能:

def update_dict2(dict2, key1, key2, value):
    newdict2 = {}
    for key1 in dict2:
        for key2 in key1:
            if key1[0] == key2[0]:
                newdict2[key1][key2] == value



x = update_dict2(DD,'aaa','ccc',12)
print(x)


DD = {'aaa' : {'bbb': 'string1','ccc': 'string2', 'ddd' : 'string3' },
 'bbb' : {'ccc':'string4','ddd':'string5','eee':'string6','fff':'string7'},
 'ccc' : {'aaa':'string8','bbb':'string9'}}



Expected results:

1. update_dict2(DD,'aaa','ccc',12)
return value:
 {'aaa': { 'bbb' : 'string1', 'ccc' : 12, 'ddd' : 'string3' },
  'bbb': {'ccc':'string4','ddd':'string5','eee':'string6','fff':'string7'},
  'ccc': { 'aaa' : 'string8', 'bbb' : 'string9' }}

2. update_dict2(DD,'aaa','ggg','string17')
return value:
{'aaa':{'bbb':'string1','ccc':12,'ddd':'string3','ggg':'string17'},
 'bbb':{'ccc':'string4','ddd':'string5','eee':'string6','fff':'string7'},
 'ccc':{'aaa':'string8','bbb':'string9'}
}

3. update_dict2(DD,'ggg','aaa','string17'):

    enter code here

return value:
{'aaa':{'bbb':'string1','ccc':12,'ddd':'string3'},
 'bbb':{'ccc':'string4','ddd':'string5','eee':'string6','fff':'string7'},
 'ccc':{'aaa':'string8','bbb':'string9'},
 'ggg':{'aaa':'string17'}}



Errors:

Error received when running a test case


  [1]: https://i.stack.imgur.com/JHA4t.png

【问题讨论】:

    标签: python-3.x


    【解决方案1】:
    '''This works'''
    
    def update_dict2(dict2, key1, key2, value):
        '''
        This function takes a two-level dicitonary and updates the values at key2 if
        key1 exists. If key1 does not exist, the function adds it to the dictionary with
        it's coinciding key2 and value.
        '''
        if key1 not in dict2:
           dict2[key1] = {key2:value}
        else:
            dict2[key1][key2] = value
        return dict2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多