I have the following sample data as a listobject in 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'}]
How can i remove the description, tour_url from this list; or how can I only keep the name and leagueid keys. I have tried a variety of solutions, but it just doesnt seem to work.
2nd question: how can I filter this list? As in mysql:
select *
from table
where leagueid = 1212
Please treat me like a new person to python, because i really am.
In fact list
does not have keys, list
has indices, and dictionary
has keys. In your case, you have a list of dictionaries, and what you need is to remove some keys (2 exactly: description and tournament_url) form each item (dictionary) of your list:
for item in my_list: # my_list if the list that you have in your question
del item['description']
del item['tournament_url']
To retrieve an item from your above list with some criteria, you can do:
[item for item in my_list if your_condition_here]
Example:
>>> [item for item in my_list if item['itemdef'] == 10541]
[{'leagueid': 1212, 'itemdef': 10541, 'name': 'Dota 2 Just For Fun'}]
Edit:
To filter my_list
items to retrieve only some keys, you can do:
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With