【问题标题】:How to add new key-value to dictionary如何将新的键值添加到字典
【发布时间】:2021-09-29 22:55:13
【问题描述】:
contacts = {'John Smith': '1-123-123-123',
            'Jane Smith': '1-102-555-5678',
            'John Doe': '1-103-555-9012'}


def add_contact(contacts, name, number):
    """
    Add a new contact (name, number) to the contacts list.
    """
    if name in contacts:
        print(name, "is already in contacts list!")
    else:
        contacts[name] = number

print(add_contact(contacts, 'new_guy', '1234'))

当我打印这个时,我得到none

但如果我添加另一行 print(contacts)

它会给我一个none 和带有'new_guy' :'1234'. 的新字典在不打印none 的情况下打印出新字典的正确方法是什么?

【问题讨论】:

  • 您正确地添加到字典中。你打印错了。您的 print 语句打印函数的结果。您的函数不返回任何内容。
  • 对。由于您的功能已就地修改,请不要打印它。只需拨打add_contact(contacts, 'new_guy', '1234'),然后拨打print(contacts)
  • 如果你只是在add_contact 函数的末尾添加return contacts,它就可以正常工作。

标签: python python-3.x dictionary


【解决方案1】:

按照您现在的方式,您正在打印函数返回的内容(没有)。您需要做的就是将函数调用和打印语句分开,如下所示:

    add_contact(contacts, 'new_guy', '1234')
    print(contacts)

【讨论】:

    【解决方案2】:
    def add_contact(name, number):
        """
        Add a new contact (name, number) to the contacts list.
        """
        if name in contacts:
            print(name, "is already in contacts list!")
        else:
            contacts[name] = number
        return contacts #put a return statement that will return the updated contacts dictionary
    
    print(add_contact('John Doe', '1234'))
    
    
    #for simplified version try a dictionary comprehension:
    #using the dict.update(), we can use a comprehension inside to iterate from the contacts itself and have a condition if the name is already exists
    contacts.update({key: value for key, value in contacts.items() if key not in contacts})
    
    #tho, we can't have a print statement that will tell if the name already exist in the contacts
    print(contacts)
    
    >>>output: {'John Smith': '1-123-123-123', 'Jane Smith': '1-102-555-5678', 'John Doe': '1-103-555-9012'}
    

    【讨论】:

      【解决方案3】:

      您正确地添加到字典中。你的打印声明是问题所在。

      改变这个:

      print(add_contact(contacts, 'new_guy', '1234'))

      你需要把它分开一些。

      add_contact(contacts, 'new_guy', '1234')
      print(contacts)
      

      另外,由于您的contacts 字典是全局声明的,您不需要将其传递给函数 应该在函数中将其命名为不同的名称,以便清楚起见。您可以将函数更改为:

      def add_contact(current_contacts, name, number):
      

      但也不要在函数内部进行更改。

      if name in current_contacts:
              print(name, "is already in contacts list!")
          else:
              current_contacts[name] = number
      

      最终代码:

      contacts = {'John Smith': '1-123-123-123',
                  'Jane Smith': '1-102-555-5678',
                  'John Doe': '1-103-555-9012'}
      
      
      def add_contact(current_contacts, name, number):
          """
          Add a new contact (name, number) to the contacts list.
          """
          if name in current_contacts:
              print(name, "is already in contacts list!")
          else:
              current_contacts[name] = number
      
      
      add_contact(contacts, 'new_guy', '1234')
      print(contacts)
      
      

      【讨论】:

      • 告诉他依赖全球是个坏建议。我会删除该建议。全局变量是邪恶的。
      • OP 的add_contact 将适用于任何联系人字典。巧合的是,它与全局同名。改为使用全局变量会减少功能。它与发布的示例没有任何区别,但应在您的评论中注明。
      • @tdelaney 是的,我只是没想到它使用了相同的名称,这正是它不应该使用相同名称的原因。我将对其进行编辑以更改它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2013-09-19
      • 1970-01-01
      • 2017-10-02
      • 2013-09-28
      • 2011-04-16
      • 2021-03-20
      相关资源
      最近更新 更多