简体   繁体   中英

Python - function to create a dictionary from a list

I'm defining a function in Python that takes a list as an argument. The function should return a dictionary from that list.

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)

The problem is that only one value it's being returned as a dictionary, isn't the code supposed to create a new entry for each person that it's found on the list?

在此处输入图像描述

You only ever create one single dictionary, regardless of how many people are in person_list . You want to create one dictionary per person. A dictionary's keys must be unique, so your for-loop simply overwrites the previous key-value pairs with the most recent one, so when you return persons , you're just returning a single dictionary containing the last person's information.

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

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

Output:

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

dicts in this case, is a list of dictionaries, one for each person.

Similar to @user10987432, but I don't like using dict because it's slow.

You could write it instead like:

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)

In addition to the solution mentioned above, if you really need dict of dicts, you can go this way and build nested dict:

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

This will give you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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