这有什么方法可以检查我的字典中是否有负值(仅整数)?
如果是,则将所有负值都更改为正值?
例如:

D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}

我想得到:
D = {'Milk': 5, 'eggs': 144, 'flour': 10, 'chocolate': 2, 'yeast': 5, 'Cornflower': 3}

最佳答案

遍历字典,然后使用abs()内置函数:

D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}
for key, value in D.items():
   D[key] = abs(value)
print(D)

输出:
{'yeast': 5, 'Milk': 5, 'flour': 10, 'chocolate': 2, 'eggs': 144, 'Cornflower': 3}

如果您想在值为负时执行其他操作,请使用if语句:
D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}
for key, value in D.items():
   if value < 0:
       print('{} is negative'.format(key))
       D[key] = abs(value)
print(D)

输出:
chocolate is negative
Milk is negative
flour is negative
{'chocolate': 2, 'Cornflower': 3, 'Milk': 5, 'flour': 10, 'yeast': 5, 'eggs': 144}

10-06 06:12