[英]Printing Python Key elements by Value in List of Dictionaries
我有一個我認為相當簡單的問題,但我無法弄清楚它的語法。
我有一個字典列表,如下所示:
[{'word': 'the', 'count': 19},
{'word': 'and', 'count': 14},
{'word': 'he', 'count': 7},
{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
我只想要一個訪問count變量並打印count = 1的每個字典的for循環。我正在尋找的output:
[{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
實現這樣的事情的最簡單方法是什么。 謝謝。
在發布問題后不久,我自己就解決了這個問題。 最簡單的方法是:
for x in array:
if x['count'] == 1:
print(x)
這將打印特定計數等於 1 的值!
您可以使用列表推導。 如果你有:
lst = [{'word': 'the', 'count': 19},
{'word': 'and', 'count': 14},
{'word': 'he', 'count': 7},
{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
你可以做:
lst2 = [d for d in lst if d['count'] == 1]
這將lst2
設置為:
[{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
您可以只創建一個列表變量, if
dict
的count
鍵的值為1
, append
就是列表變量的dict
!
如圖所示!
代碼:
result = []
list_of_dict = [{'word': 'the', 'count': 19},
{'word': 'and', 'count': 14},
{'word': 'he', 'count': 7},
{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
for i in list_of_dict:
if i["count"] == 1:
result.append(i)
print(result)
Output:
[{'word': 'left', 'count': 1},
{'word': 'dead', 'count': 1},
{'word': 'its', 'count': 1},
{'word': 'head', 'count': 1},
{'word': 'galumphing', 'count': 1},
{'word': 'arm', 'count': 1},
{'word': 'beamish', 'count': 1},
{'word': 'boy', 'count': 1},
{'word': 'o', 'count': 1}]
這是最簡單的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.