将python字典值设置为全零

问题描述 投票:0回答:1

如果我有这个字典:

dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8]], "key2" : [4, 5] }

如何将所有值设置为0?输出应为:

dict1 = { "Key1" : [0,0,0][0,0,0], "key2" : [0,0] }
python
1个回答
3
投票

您可以使用递归函数来做到这一点,该函数将传递给它的列表的每个元素归零:

dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8]], "key2" : [4, 5] }

def zero(e):
    if type(e) is list:
        return [zero(v) for v in e]
    return 0

dict1 = { k : zero(v) for k, v in dict1.items() }
print(dict1)

输出:

{'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}

请注意,这将生成一个new字典,而不是对原始字典进行变异。

© www.soinside.com 2019 - 2024. All rights reserved.