我有以下示例数据作为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
请像对待python的新手一样对待我,因为我确实是。
实际上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'}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句