问题描述:

dict = {'1': 10, '2': 7, '3': -10}

for k,v in dict.items():

if v < 0:

v = 0

Can someone give me the a loop to look in dict and find negative values and set them to 0 thank you. python 3 as well.

网友答案:

Since you have to check all of the items in the dictionary, you are going to use a for loop like you did, however you will have to save the 0 into the dictionary, like so:

for key in dict:
    if dict[key] < 0:
        dict[key] = 0

You weren't saving the new value into the dictionary, so no values in the dictionary were being changed.

It's worth noting that the elements in a dictionary are stored randomly, so while this loop will change all the negative values to 0, there is no guarantee in which order they will be changed.

相关阅读:
Top