简体   繁体   English

Python 将字典中的负值更改为正值

[英]Python change negative values to positive values in dictionary

this have any way to check if i have negtive values (only integers) in my dictionary?这有什么方法可以检查我的字典中是否有负值(只有整数)? And if yes to change all the negative values to positive values?如果是,将所有负值更改为正值? For example:例如:

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

And i want to get:我想得到:

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

Iterate through the dictionary then use the abs() built-in function:遍历字典,然后使用内置的abs() function:

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)

Output: Output:

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

If you want to do something else when the value is negative, use an if statement:如果您想在值为负数时执行其他操作,请使用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)

Output: Output:

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

Just use abs() to change the values to absolute values:只需使用abs()将值更改为绝对值:

>>> {k: abs(v) for k, v in D.items()}
{'Milk': 5, 'eggs': 144, 'flour': 10, 'chocolate': 2, 'yeast': 5, 'Cornflower': 3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM