簡體   English   中英

使用字典條目進行列表理解

[英]list comprehension using dictionary entries

試圖弄清楚我如何能夠對以下內容使用列表理解:

我有一本字典:

dict = {}
dict ['one'] = {"tag":"A"}
dict ['two'] = {"tag":"B"}
dict ['three'] = {"tag":"C"}

我想創建一個列表(我們稱之為“列表”),該列表由每個鍵的每個“標簽”值填充,即

['A', 'B', 'C']

有沒有一種有效的方法來使用列表理解呢? 我在想類似的東西:

list = [x for x in dict[x]["tag"]]

但顯然這不太有效。 任何幫助表示贊賞!

嘗試這個:

d = {'one': {'tag': 'A'},
     'two': {'tag': 'B'},
     'three': {'tag': 'C'}}

tag_values = [d[i][j] for i in d for j in d[i]]

>>> print tag_values
['C', 'B', 'A']

您可以在以后對列表進行排序。

如果內部字典中還有其他鍵/值對,除了“標簽”之外,您可能還需要指定“標簽”鍵,如下所示:

tag_value = [d[i]['tag'] for i in d if 'tag' in d[i]]

對於相同的結果。 如果'tag'始終存在,請刪除if 'tag' in d[i]部分中if 'tag' in d[i]

附帶說明一下,將list稱為“列表”絕不是一個好主意,因為它是Python中的保留字。

這是一個額外的步驟,但可以獲得所需的輸出,並且避免使用保留字:

d = {}
d['one'] = {"tag":"A"}
d['two'] = {"tag":"B"}
d['three'] = {"tag":"C"}
new_list = []
for k in ('one', 'two', 'three'):
    new_list += [x for x in d[k]["tag"]]

print(new_list)

您可以嘗試以下方法:

[i['tag'] for i in dict.values()]

我會做這樣的事情:

untransformed = {
    'one': {'tag': 'A'},
    'two': {'tag': 'B'},
    'three': {'tag': 'C'},
    'four': 'bad'
}
transformed = [value.get('tag') for key,value in untransformed.items() if isinstance(value, dict) and 'tag' in value]

聽起來您還想嘗試從JSON中獲取一些信息,您可能想研究一下https://stedolan.github.io/jq/manual/

暫無
暫無

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

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