簡體   English   中英

Python - 從列表創建字典的函數

[英]Python - function to create a dictionary from a list

我在 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)

問題是它只有一個值作為字典返回,難道代碼不應該為它在列表中找到的每個人創建一個新條目嗎?

在此處輸入圖像描述

無論person_list中有多少人,您只能創建一個字典。 你想為每個人創建一本字典。 字典的鍵必須是唯一的,所以你的 for 循環只是用最近的鍵值對覆蓋以前的鍵值對,所以當你return 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 dicts,你可以這樣做並構建嵌套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'}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM