【发布时间】:2020-08-25 10:27:38
【问题描述】:
我是 Python 新手,我正在编写一个函数,用于合并来自不同用户输入的两个字典。它有效,但在我看来,我的代码不必要又长又麻烦。有没有办法让它更简单和流畅?代码如下:
key1 = int(input("Give an integer as first key"))
key2 = int(input("Give an integer as second key"))
value1 = input("Give a a first value")
value2 = input("Give a second value")
class_list1 = {}
class_list2 = {}
class_list1[key1] = value1
class_list2[key2] = value2
def merge_dictionaries(x,y):
z = {**x,**y}
print("The merged dictionary is : ")
return z
print(merge_dictionaries(class_list1, class_list2))
输出:
Give an integer as first key 1
Give an integer as second key 2
Give a a first value value1
Give a second value value2
The merged dictionary is :
{1: 'value1', 2: 'value2'}
【问题讨论】:
-
除了
return {**x,**y},你不能比你已经拥有的更短。顺便说一句,merge_dictionary中的print语句没有打印出任何有用的信息。
标签: python function dictionary