如何从列表python中的多个字典中删除键

时间:2016-12-01 16:49:32

标签: python list python-3.x

我在python中将以下示例数据作为listobject。

[{'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

请把我当作蟒蛇的新人,因为我真的很喜欢。

3 个答案:

答案 0 :(得分:3)

实际上list没有密钥,list有索引,dictionary有密钥。在您的情况下,您有一个词典列表,您需要的是从列表的每个项目(字典)中删除一些键(2个确切地说:description和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'}]

答案 1 :(得分:0)

对于第一个问题:

for item in table:
    item.pop(tournament_url)

关于第二个问题:

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

答案 2 :(得分:-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

中的理解