簡體   English   中英

如何從字典列表中創建三個單獨的值列表,其中每個字典都有三個鍵

[英]How to create three separate lists of values from a list of dictionaries where each dictionary has three keys

我是 Python 的新手。 對於有經驗的開發人員和編碼人員來說,我的問題可能很簡單,但我一直無法找到答案。

我正在通過數據庫查詢檢索一些數據。 我已經成功地將查詢返回的每一行組織為一個字典,該字典具有三個鍵和每個鍵對應的值。 本質上,我已將查詢返回的所有數據行組織到字典列表中。

字典列表看起來有點像這樣:

[
    {'Date': date1, 'price': price1, 'itemnumber': number1},
    {'Date': date2, 'price': price2, 'itemnumber': number2},
    ...
]

如何將此字典列表轉換為對應於每個鍵的三個單獨列表,即DatePriceitemnumber

使用列表推導式

date = [d['Date'] for d in list_of_dicts]
price = [d['price'] for d in list_of_dicts]
itemnumber = [d['itemnumber'] for d in list_of_dicts]

也可以在可讀性較差的單行中執行此操作:

date, price, itemnumber = zip(*[(d['Date'], d['price'], d['itemnumber']) for d in list_of_dicts])

或相同但使用operator.itemgetter

from operator import itemgetter
date, price, itemnumber = zip(*map(itemgetter('Date', 'price', 'itemnumber'), list_of_dicts))

在第二種情況下map(list, ...)使用map(list, ...)將返回的元組轉換為列表。

您可以結合使用 listcomp 和 dictcomp:

In [95]: ds
Out[95]: 
[{'Date': 'date1', 'itemnumber': 'number1', 'price': 'price1'},
 {'Date': 'date2', 'itemnumber': 'number2', 'price': 'price2'}]

In [96]: {key: [subdict[key] for subdict in ds] for key in ds[0]}
Out[96]: 
{'Date': ['date1', 'date2'],
 'itemnumber': ['number1', 'number2'],
 'price': ['price1', 'price2']}

請注意,我們有三個單獨的列表,它們只是更方便地作為值存儲在字典中。 這樣,如果我們決定要添加額外的特征(比如“購買者”),我們就不需要更改任何邏輯。

# Defining lists
dates = []
prices = []
item_numbers = []
# Loop through list
for dictionary in your_list:
    dates.append(dictionary["Date"]) # Add the date to dates
    prices.append(dictionary["price"]) # Add the price to prices
    # Add item number to item_numbers
    item_numbers.append(dictionary["itemnumber"])
for (field,values) in [(field,
            [result.get(field) for result in results]
        ) for field in results[0].keys()]:
    # this is ugly, but I can't see any other legal way to
    # dynamically set variables.
    eval "%s=%s" % (field, repr(value))

編輯為不[非法]修改locals()字典:(

暫無
暫無

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

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