Reputation: 11
If I have this dict:
dict1 = {"Key1": [[1, 3, 4], [2, 5, 8]], "key2": [4, 5]}
How can I set all the values to 0
?
Output should be like this:
dict1 = {"Key1": [[0,0,0], [0,0,0]], "key2": [0,0]}
Upvotes: 0
Views: 70
Reputation: 17322
you can mutate your dict1
values so that the most inner lists to have only 0
as elements:
def change_to_zero(nested_list):
if isinstance(nested_list[0], list):
for l in nested_list:
change_to_zero(l)
else:
nested_list[::] = [0] * len(nested_list)
change_to_zero(list(dict1.values()))
print(dict1)
output:
{'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}
this approach assumes that your dict
values are lists of different levels of nestedness and the most inner list doesn't have lists as elements, only integers (for your example)
Upvotes: 0
Reputation: 147206
You can do this with a recursive function that zeros each element of a list or dictionary that is passed to it:
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]
elif type(e) is dict:
return {k : zero(v) for k, v in e.items()}
return 0
dict1 = zero(dict1)
print(dict1)
Output:
{'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}
Note that this generates a new dictionary rather than mutating the original one.
Upvotes: 3
Reputation: 123491
You can modify the dictionary "in-place" — i.e. without replacing it with a new one — via a relatively simple recursive function:
def zero_values(obj):
if isinstance(obj, dict):
for k, v in obj.items():
obj[k] = zero_values(v)
return obj
elif isinstance(obj, list):
for i, v in enumerate(obj):
obj[i] = zero_values(v)
return obj
else:
return 0
dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8] ], "key2" : [4, 5] }
zero_values(dict1)
print(dict1) # -> {'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}
Upvotes: 1