2016-12-01 107 views
0

我有以下示例數據作爲python中的listobject。如何刪除列表中的多個字典中的鍵python

[{'itemdef': 10541, 
    'description': 'Dota 2 Just For Fun tournament. ', 
    'tournament_url': 'https://binarybeast.com/xDOTA21404228/', 
    'leagueid': 1212, 
    'name': 'Dota 2 Just For Fun'}, 
{'itemdef': 10742, 
    'description': 'The global Dota 2 league for everyone.', 
    'tournament_url': 'http://www.joindota.com/en/leagues/', 
    'leagueid': 1640, 
    'name': 'joinDOTA League Season 3'}] 

如何從此列表中刪除說明tour_url;或者我怎麼能只保留名字和聯盟鍵。我嘗試了各種解決方案,但它似乎並不奏效。

第二個問題:如何過濾這個列表?如在mysql中:

select * 
from table 
where leagueid = 1212 

請把我當成一個像python一樣的新人,因爲我真的是。

回答

2

其實list沒有鑰匙,list有指標,並dictionary有鑰匙。你的情況,你有字典的列表,你需要的是刪除一些按鍵:您的清單(2恰好說明和tournament_url)形成的每個項目(字典):

for item in my_list: # my_list if the list that you have in your question 
    del item['description'] 
    del item['tournament_url'] 

從檢索項目你的一些標準上面所列內容,你可以這樣做:

[item for item in my_list if your_condition_here] 

例子:

>>> [item for item in my_list if item['itemdef'] == 10541] 
[{'leagueid': 1212, 'itemdef': 10541, 'name': 'Dota 2 Just For Fun'}] 

編輯:

要過濾my_list項目只檢索某些鍵,你可以這樣做:

keys_to_keep = ['itemdef', 'name'] 

res = [{ key: item[key] for key in keys_to_keep } for item in my_list] 
print(res) 
# Output: [{'itemdef': 10541, 'name': 'Dota 2 Just For Fun'}, {'itemdef': 10742, 'name': 'joinDOTA League Season 3'}] 
+0

是否存在'del'和'item.pop'之間的區別? – rassar

+0

等等,所以我有一個詞典列表?該死,非常感謝。我一直被困在這個狗屎上。 – Adam

+0

@rassar'item.pop('key')'也會返回密鑰的值,所以當我們需要讀取和刪除對象時使用它。 – Pavel

0

對於第一個問題:

for item in table: 
    item.pop(tournament_url) 

對於第二個問題:

[item for item in table if item[leagueid] == 1212] 
+0

你能解釋一下如何使用第二一段代碼? – Adam

+0

@Adam有三個等同的變體可以這樣做:http://pastebin.com/miyEgkVY – Pavel

-1

所以,你有什麼就有什麼詞典列表。要從詞典中tournament_url關鍵,我們將使用字典解析

my_list = [{k:v for k, v in d.items() if k != 'tournament_url'} for d in my_list] 

瞭解更多關於內涵在official python documentation

+1

這將重新創建列表和所有字典。迭代列表中刪除不需要的密鑰更容易,更快捷。 – Holloway

+0

print [{key:key的值,d [x] .items()的值,如果key!='tournament_url'和key!='description'} for x in range(len(d))] –

相關問題