Python-从列表创建字典的函数

Python-从列表创建字典的函数,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我正在用Python定义一个函数,它将列表作为参数。函数应该从该列表中返回一个字典 persons = [['john','doe'],['tony','stark']] def build_agenda(person_list): """Return a dictionary about a list of information of people""" persons = {} for person in person_list: persons[

我正在用Python定义一个函数,它将列表作为参数。函数应该从该列表中返回一个字典

persons = [['john','doe'],['tony','stark']]

def build_agenda(person_list):
    """Return a dictionary about a list of information of people"""
    persons = {}
    for person in person_list:
        persons['first_name'] = person[0]
        persons['last_name'] = person[1]
    return persons

output = build_agenda(persons)
print(output)
问题是,它只返回一个值作为字典,代码不应该为列表中找到的每个人创建一个新条目吗


无论
人员列表中有多少人,您都只能创建一本词典。您希望每人创建一本词典。字典的键必须是唯一的,因此for循环只会用最新的键值对覆盖以前的键值对,因此当
返回persons
时,只返回一个包含最后一个人信息的字典

persons = [["John", "Doe"], ["Tony", "Stark"]]

dicts = [dict(zip(("first_name", "last_name"), person)) for person in persons]
print(dicts)
输出:

[{'first_name': 'John', 'last_name': 'Doe'}, {'first_name': 'Tony', 'last_name': 'Stark'}]

dicts
在本例中,是一个字典列表,每个人一本。

类似于@user10987432,但我不喜欢使用
dict
,因为它很慢

你可以这样写:

persons = [['john','doe'],['tony','stark']]

def build_agenda(person_list):
    """Return a list of dictionaries about a list of information of people"""
    persons = [{'first_name': first, 'last_name': last} 
               for first, last in persons]
    return persons

output = build_agenda(persons)
print(output)

除了上面提到的解决方案之外,如果您确实需要dict of dict,您可以通过这种方式构建嵌套dict:

persons = [['john','doe'],['tony','stark']]    
result = {idx: {'first_name': person[0], 'last_name': person[1]} for idx, person in enumerate(persons)}
这将为您提供:

{0: {'first_name': 'john', 'last_name': 'doe'}, 1: {'first_name': 'tony', 'last_name': 'stark'}}

不要将文本作为图像。在第一次循环后的每次迭代中,您都会覆盖字典的“first_name”和“last_name”。在每次迭代中,您都会重新定义dict中相同键的值(last_name和first_name)。