簡體   English   中英

如何從python字典中獲取列表列表?

[英]How to get a list of lists from a dictionary of dictionaries in python?

我想將字典字典轉換為列表列表。 字典的格式是:

{0: {’apple’: 2, ’orange’: 5, ’banana’: 4}, 1: {'apple’: 2, ’orange’: 1, ’banana’: 7}}

鍵從 0,1,2,3 等開始的地方......字典中鍵的值是那個水果的數量。 我正在嘗試列出如下所示的列表:

 [[2, 5, 4], [2, 1, 7]]

其中每個子列表是原始鍵(0、1、2、3 等...)。 因此,如果有 4 個詞典,則有 4 個子列表。

我更喜歡沒有花哨的代碼和導入。 我該怎么做呢? 任何幫助將不勝感激!

您可以使用values()在簡單的列表理解中執行此操作:

myDict = {0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}

arr = [list(d.values()) for d in myDict.values()]
#[[2, 5, 4], [2, 1, 7]]
x = {0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}


print([list(z.values()) for y,z in x.items()])
x={0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}
lst=[]
lst1=[]
for key,iteam in x.items():
    for k,itm in iteam.items():
        lst.append(itm)
    print(lst)
    lst1.append(lst)
    lst=[]  

沒問題親愛的?

暫無
暫無

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

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