📜  Python - 最小值键分配

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

Python - 最小值键分配

给定两个字典,任务是编写一个Python程序,为两个字典中的匹配键分配最小值。

例子:

方法 #1:使用字典理解+ min() + items()

在这种情况下,使用 min() 提取最少的键值。字典理解用于重建具有修改值的字典。

Python3
# Python3 code to demonstrate working of
# Minimum value key assignment
# Using dictionary comprehension + min() + items()
  
# initializing dictionaries
test_dict1 = {"gfg": 1, "is": 7, "best": 8}
test_dict2 = {"gfg": 2, "is": 2, "best": 10}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# using min() to assign min values
res = {key: min(val, test_dict2[key]) for key, val in test_dict1.items()}
  
# printing result
print("The minimum value keys : " + str(res))


Python3
# Python3 code to demonstrate working of
# Minimum value key assignment
# Using dict() + min() + zip()
  
# initializing dictionaries
test_dict1 = {"gfg": 1, "is": 7, "best": 8}
test_dict2 = {"gfg": 2, "is": 2, "best": 10}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# using min() to assign min values
# dict() for conversion of result to dictionary
res = dict([min(i, j) for i, j in zip(test_dict1.items(), test_dict2.items())])
  
# printing result
print("The minimum value keys : " + str(res))


输出:

The original dictionary 1 is : {'gfg': 1, 'is': 7, 'best': 8}
The original dictionary 2 is : {'gfg': 2, 'is': 2, 'best': 10}
The minimum value keys : {'gfg': 1, 'is': 2, 'best': 8}

方法 #2:使用dict() + min() + zip()

在这里,为了更好的比较, zip()用于获取要比较的值, min()用于获取键的最小值。然后dict()用于将结果转换为字典。

蟒蛇3

# Python3 code to demonstrate working of
# Minimum value key assignment
# Using dict() + min() + zip()
  
# initializing dictionaries
test_dict1 = {"gfg": 1, "is": 7, "best": 8}
test_dict2 = {"gfg": 2, "is": 2, "best": 10}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# using min() to assign min values
# dict() for conversion of result to dictionary
res = dict([min(i, j) for i, j in zip(test_dict1.items(), test_dict2.items())])
  
# printing result
print("The minimum value keys : " + str(res))

输出:

The original dictionary 1 is : {'gfg': 1, 'is': 7, 'best': 8}
The original dictionary 2 is : {'gfg': 2, 'is': 2, 'best': 10}
The minimum value keys : {'gfg': 1, 'is': 2, 'best': 8}