python - 通过函数合并来自用户输入的两个字典
问题描述
我是 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'}
解决方案
您可以将用户输入直接保存在字典中而无需合并:
userStorage = {}
for inputNum in range(2):
# Temporary variables
_key, _value = None, None
while not (_key and _value):
# both variables must have a value!
# 'validate' at least the key as integer
try:
_key = int(input("Give an integer as key#%d:" % inputNum))
except:
print("No integer entered!")
continue
_value = input("Give a value for key#%d:" % inputNum)
if _key and _value:
userStorage[_key] = _value
break
print(userStorage)
输出:
Give an integer as key#0:asd
No integer entered!
Give an integer as key#0:9
Give a value for key#0:foo
Give an integer as key#1:10
Give a value for key#1:bar
{9: 'foo', 10: 'bar'}
请注意,“最短”版本可能是(但现在代码容易出现错误的用户输入):
userInput = lambda x, y: int(input("Give an integer as key#%d:" % x)) if y == 0 else input("Give a value for key#%d:" % x)
userStorage = {userInput(x, 0): userInput(x, 1) for x in range(2)}
print(userStorage)
输出:
Give an integer as key#0:87
Give a value for key#0:foo
Give an integer as key#1:88
Give a value for key#1:baz
{87: 'foo', 88: 'baz'}
推荐阅读
- javascript - jQuery包装所有标题和下面的元素,直到下一个标题
- azure-lab-services - 无法通过 Azure 实验室服务虚拟机池连接到 VM。RDP 不下载
- python - 将 series.map 与多键字典一起使用
- angular - 角度发送文件到服务器
- jquery - 如何按特定顺序将元素添加到列表中?
- r - shp的R函数
- mysql - 从组中添加值
- swift - ORSSerialPort.send 不发送任何内容
- javascript - 如何在 x 轴上设置 max/min 以在 Chart.js 中显示时间范围?
- php - 关于服务器日期和 laravel cron 作业的问题