If I have a dictionary with each key having a list of values for example:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}
And I want to create a loop statement to go through each value within the lists and change the value within my dictionary to 0 for each negative value. I can create a loop statement to go through each value and check if the value is negative but I can't figure out how to amend the dictionary directly:
for keys, values in my_dict.items():
for value in values:
if value < 0:
value=0
How to I alter that last line (or do I have to change more lines) to be able to amend my dictionary directly to replace the negative values with 0?
Thanks in advance
One approach is to iterate over the .items
of the dictionary and override each value directly using enumerate
to keep track of the indices:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}
for key, value in my_dict.items():
for i, val in enumerate(value):
value[i] = 0 if val < 0 else val
print(my_dict)
Output
{'key1': [1, 6, 7, 0], 'key2': [2, 5, 10, 0], 'key3': [0, 1, 0, 6]}
Alternative using the slicing operator and a list comprehension :
for key, value in my_dict.items():
value[:] = [0 if val < 0 else val for val in value]
Some other useful resources:
在嵌套理解中使用 max:
my_dict = {k: [max(0, v) for v in vals] for k, vals in my_dict.items()}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.