我有這個結構:
attributes_json = {
"attributes": [
{
"color": "blue",
"id": 78923,
{
"color": "red",
"id": 321
我只想選擇“顏色”鍵及其值,然后將它們放入串列中,我該如何在 Python 中做到這一點?
到目前為止我已經嘗試過了,但它只給出了第一種顏色:
lista = [item for item in attributes_json['attributes'][0]['color']]
uj5u.com熱心網友回復:
我假設該結構是一個帶有鍵“屬性”的字典,而“屬性”是一個字典串列,每個字典都有一個鍵“顏色”。您有正確的想法,但您只訪問第一個條目。您需要像這樣遍歷字典串列:
attributes_list = attributes_json["attributes"]
colors = []
for entry in attributes_list:
color = entry["color"]
colors.append(color)
在串列理解形式中,
colors = [entry["color"] for entry in attributes_json["attributes"]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430246.html
上一篇:根據其他串列中的條件列舉串列
