繁体   English   中英

如何向字典添加新的键值

[英]How to add new key-value to dictionary

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

你需要把它分开一些。

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

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

def add_contact(current_contacts, name, number):

但也不要在 function 中进行更改。

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)

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

    add_contact(contacts, 'new_guy', '1234')
    print(contacts)
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'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM