如何删除列表中的多个字典中的键python
我有以下示例数据作为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一样的新人,因为我真的是。
其实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'}]
所以,你有什么就有什么词典列表。要从词典中tournament_url
关键,我们将使用字典解析
my_list = [{k:v for k, v in d.items() if k != 'tournament_url'} for d in my_list]
了解更多关于内涵在official python documentation
这将重新创建列表和所有字典。迭代列表中删除不需要的密钥更容易,更快捷。 – Holloway
print [{key:key的值,d [x] .items()的值,如果key!='tournament_url'和key!='description'} for x in range(len(d))] –
是否存在'del'和'item.pop'之间的区别? – rassar
等等,所以我有一个词典列表?该死,非常感谢。我一直被困在这个*上。 – Adam
@rassar'item.pop('key')'也会返回密钥的值,所以当我们需要读取和删除对象时使用它。 – Pavel