📜  Python – 将字典值转换为绝对值

📅  最后修改于: 2022-05-13 01:55:45.131000             🧑  作者: Mango

Python – 将字典值转换为绝对值

给定一个字典,将其值转换为绝对值。

方法 #1:使用循环 + abs()

这是可以执行此任务的方式之一。在此,我们使用循环对字典的每个值进行迭代,并使用 abs() 执行绝对幅度转换。

Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using loop + abs()
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using abs() to perform conversion
# from negative to positive values
for ele in test_dict:
    test_dict[ele] = abs(test_dict[ele])
 
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))


Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using dictionary comprehension + abs()
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# dictionary comprehension using to compile result
# items() used to extract dictionary keys and values.
res = {key : abs(val) for key, val in test_dict.items()}
 
# printing result
print("Dictionary after absolute conversion : " + str(res))


输出
The original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}

方法 #2:使用字典理解 + abs()

此任务类似于上述方法。不同之处在于使用字典理解而不是循环来执行通过键的迭代任务。

Python3

# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using dictionary comprehension + abs()
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# dictionary comprehension using to compile result
# items() used to extract dictionary keys and values.
res = {key : abs(val) for key, val in test_dict.items()}
 
# printing result
print("Dictionary after absolute conversion : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}