【问题标题】:Merge two dictionaries from user input through a function通过函数合并来自用户输入的两个字典
【发布时间】: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


【解决方案1】:

您可以将用户输入直接保存在字典中而无需合并:

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'}

【讨论】:

    【解决方案2】:

    试试下面的

    key1 = int(input("Give an integer as first key"))
    key2 = int(input("Give an integer as second key"))
    x= y= {}
    x[key1]=input("Give a a first value")
    y[key2]=input("Give a second value")
    print({**x,**y})
    

    【讨论】:

      【解决方案3】:

      这里对您的原始文件进行了一些微调(简化功能并尽可能将input 换行):

      class_list1 = {}
      class_list2 = {}
      
      key1 = int(input("Give an integer as first key"))
      key2 = int(input("Give an integer as second key"))
      
      class_list1[key1] = input("Give a a first value")
      class_list2[key2] = input("Give a second value")
      
      def merge_dictionaries(x,y):
          return {**x,**y}
      
      print("The merged dictionary is : {}".format(merge_dictionaries(class_list1, class_list2)))
      

      以上是我在保留原始代码逻辑的同时节省行数的方法。

      如果您对其他方法持开放态度,您可以使用input,然后使用split 将其切成创建字典所需的部分。这里的代码更短,可以采用可变数量的键:值对,但input 的结构更复杂:

      s = input('Enter int:string pairs, separated by commas\n').split(',')
      d = {int(p.split(':')[0]) : p.split(':')[-1] for p in s}
      print("The merged dictionary is : {}".format(d))
      

      所以input1:a,2:b,3:c 给出{1: 'a', 2: 'b', 3: 'c'}

      【讨论】:

        【解决方案4】:

        您的代码不会太长,没有重构。
        看看代码重构。

        创建一个获取输入的函数,一个创建字典并使用主函数

                 def merge_dictionaries(x,y):
                    z = {**x,**y}
                    print("The merged dictionary is : {0} ".format(z))
                    return z
        
                 def main:
                     class_list1,class_list2 = function_input_dictionary() #function that returns dicts
                     key1,key2 = function_input_key() #function that returns input of key
                     value1,value2 = function_input_value() # function that returns values
                     print(merge_dictionaries(class_list1, class_list2))
        
        #look for design patterns and double return of parameters
                 
        

        【讨论】:

          【解决方案5】:

          试试下面这个你会发现它很有帮助,因为在我的例子中你可以通过修改名为length的变量来简单地合并两个以上的字典

          示例

          length = 2
          key = 0
          value = ''
          class_list = {}
          for i in range(1, length):
              key = int(input(f"Give an integer as {i} key: "))
              value = input(f"Give a a {i} value: ")
              class_list[key] = value
          
          
          def merge_dictionaries(x,y):
              print("The merged dictionary is : ")
              return {**x,**y}
              
          print(merge_dictionaries(class_list, class_list))
          

          【讨论】:

            【解决方案6】:

            尝试像这样创建字典,而不是使用不同的变量。它不会改变预期的输出。

            class_list1[int(input("Give an integer as first key"))] = input("Give a a first value")
            
            class_list2[int(input("Give an integer as second key"))] = input("Give a second value")
            

            【讨论】:

            • 这里不需要像在 scala 或函数式编程中那样的一行缩进命令。他正在寻求帮助以提高代码的可读性,将所有内容放在一行中,有时会使代码更难阅读。
            猜你喜欢
            • 2022-11-25
            • 1970-01-01
            • 1970-01-01
            • 2023-02-03
            • 1970-01-01
            • 1970-01-01
            • 2019-06-04
            • 1970-01-01
            • 2015-10-07
            相关资源
            最近更新 更多