如何定义一个将列表转换为字典的函数,同时在没有键值 (Python3) 的地方插入 'None'?

How to define a function that will convert list into dictionary while also inserting 'None' where there is no value for a key (Python3)?

假设我们有这样一个 contact_list:

[["Joey", 30080],["Miranda"],["Lisa", 30081]]

所以本质上 "Miranda" 没有邮政编码,但是有了我想定义的功能,我希望它能自动检测到它并将 "None" 添加到她的值槽中,比如这个:

{
"Joey": 30080,
"Miranda": None,
"Lisa": 30081
}

到目前为止我有这个,它只是将列表转换为字典:

def user_contacts(contact_list):
    dict_contact = dict(contact_list)
    print(dict_contact)

不知道我从这里要去哪里,就编写代码为 "Miranda" 添加 None 而言。目前,我只是收到一条错误消息,指出第一个元素 ("Miranda") 需要两个长度而不是一个。

最终我只想在定义的函数中传递任何列表,如上面的列表:user_contacts 并且再次能够将上面的字典作为输出。

user_contacts([["Joey", 30080],["Miranda"],["Lisa", 30081]]) 

试试这个:

def user_contacts(contact_list):
    dict_contact = dict((ele[0], ele[1] if len(ele) > 1 else None) for ele in 
    contact_list)
    print(dict_contact)

这就是您可以执行的操作。您可以检查列表中某个元素的 len 是否符合预期(在本例中,名称和邮政编码为 2)。那么如果它没有达到预期,你可以添加 "none":

contacts = [["Joey", 30080], ["Miranda"], ["Lisa", 30081]]
contacts_dict = {}
for c in contacts:
    if len(c) < 2:
        c.append('None')
    contacts_dict.update({c[0]: c[1]})
print(contacts_dict)

输出为:

{'Joey': 30080, 'Miranda': 'None', 'Lisa': 30081}