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

标签 python python-3.x dictionary numbers

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

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}

关于Python将字典中的负值更改为正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61307403/

相关文章:

python - 如何获取 TFRecord 文件中包含的条目总数?

python - 填充 Django 模型字段效果不佳

python - 如何使用类方法作为参数(变量)?

python - 无法解析从套接字接收的python中的Ctype结构

c++ - MapReduce - 直接插入 map 中 vector<int> 的第一个位置

python - 在 Python 中使用 NumPy 打印格式

python - 在 python 3 中将十六进制解码为十进制的问题

python - Pyqt5 如何避免无限循环卡住程序?

python - 从无组织的 csv 和 python 中现有的字典键创建子字典

python - 在不知道键的情况下查找字典值的类型