簡體   English   中英

根據字典列表中的不同鍵獲取多個列表

[英]Getting multiple list based on the different keys from a list of dictionaries

我有一個這樣的字典列表:

temp = [
    {
        "item": "apple",
        "id": 1
    },
    {
        "item": "ball",
        "id": 2
    },
    {
        "item": "cake",
        "id": 3
    }
]

我想要兩個列表:

["apple", "ball", "cake"]
[1, 2, 3]

我們可以使用列表推導來做到這一點嗎?

我已經這樣做了:

list_item=[]
list_id=[]
for val in temp:
    list_item.append(val["item"])
    list_id.append(val["id"])

使用字典鍵item將值存儲在l1中,使用id將值存儲在l2中。

q = [
    {
        "item": "apple",
        "id": 1
    },
    {
        "item": "ball",
        "id": 2
    },
    {
        "item": "cake",
        "id": 3
    }
]

l1 = [dic['item'] for dic in q]
l2 = [dic['id'] for dic in q]

在一個循環中:

l1,l2 = [],[]
for dic in q:
    l1.append(dic['item'])
    l2.append(dic['id'])
x =  {"item": "apple","id": 1}
y = json.loads(x)
a[0]=y["item"]
b[0]=y["id"]

你可以這樣嘗試

看到這個: https://www.w3schools.com/python/python_json.asp

暫無
暫無

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

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