如何在Python列表中从多个字典中删除键

2024-05-16 13:15:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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'}]

我怎样才能从这个列表中删除描述、旅游网址;或者我怎样才能只保留姓名和联盟ID的密钥。我试过各种各样的解决办法,但似乎都不管用。在

第二个问题:如何筛选此列表?在mysql中:

^{pr2}$

请像对待python的新人一样对待我,因为我真的是。在


Tags: 数据namecomurl示例列表fordescription
3条回答

所以你有一个字典列表。要从字典中删除tournament_url键,我们将使用字典理解

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

阅读更多关于official python documentation理解的信息

事实上,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']

要使用某些条件从上面的列表中检索项目,可以执行以下操作:

^{pr2}$

示例:

>>> [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'}]

对于第一个问题:

for item in table:
    item.pop(tournament_url)

关于第二个问题:

^{pr2}$

相关问题 更多 >