Adam Adam - 1 year ago 134
Python Question

How to delete keys from multiple dictionaries in a list python

I have the following sample data as a listobject in python.

[{'itemdef': 10541,
'description': 'Dota 2 Just For Fun tournament. ',
'tournament_url': '',
'leagueid': 1212,
'name': 'Dota 2 Just For Fun'},
{'itemdef': 10742,
'description': 'The global Dota 2 league for everyone.',
'tournament_url': '',
'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.

Answer Source

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]


>>> [item for item in my_list if item['itemdef'] == 10541]
[{'leagueid': 1212, 'itemdef': 10541, 'name': 'Dota 2 Just For Fun'}]


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]
# Output: [{'itemdef': 10541, 'name': 'Dota 2 Just For Fun'}, {'itemdef': 10742, 'name': 'joinDOTA League Season 3'}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download