gpt4 book ai didi

python - 如何根据键值和嵌套值编辑嵌套字典中的值

转载 作者:行者123 更新时间:2023-11-30 22:20:22 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数将遍历嵌套字典并将键的值添加到嵌套值,并创建一个新的嵌套键值对。例如这个输入:

current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13}, 4: {'int1': 14}, 
5: {'int1': 15}}

输出看起来像这样:

new_dict = {1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2', 14}, 
3: {'int1': 13, 'int2', 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2', 20}}

我正在使用一个非嵌套字典,其类似于添加键值对以使用以下方法创建新值:

int_dict = {1: 11, 2: 12, 3: 13, 4: 14, 5: 15}
new_dict2 = {}

def func2(k, v):
new_k = k + v
return new_k

for k, v in integer_dictionary.items():
new_dict2[k] = func2(k, v)

并返回:

{1: 12, 2: 14, 3: 16, 4: 18, 5: 20}

理想情况下,我希望构建此函数以便能够处理如上所述的嵌套字典,但我不确定如何处理嵌套元素的迭代。

最佳答案

您可以使用字典理解:

current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13}, 4: {'int1': 14}, 5: {'int1': 15}}
new_dict = {a:{**b, 'int2':b['int1']+a} for a, b in current_dict.items()}

输出:

{1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2': 14}, 3: {'int1': 13, 'int2': 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2': 20}}

编辑:没有理解:

def funct2(k, v):
return {**v, 'int2':v['int1']+k}

for a, b in current_dict.items():
current_dict[a] = funct2(a, b)

输出:

{1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2': 14}, 3: {'int1': 13, 'int2': 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2': 20}}

关于python - 如何根据键值和嵌套值编辑嵌套字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com