Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter items by value in dict

I have a dict setup like so:

deck = [{
         'name': 'drew',
         'lvl': 23,
         'items': ['sword', 'axe', 'mana_potion']},
        {
         'name': 'john',
         'lvl': 23,
         'items': ['sword', 'mace', 'health_potion']}]

This is a basic example of what it looks like, I need a way to filter (copy only the {characters}) that match certain values, such as I want only characters that are level 23, or that are carrying a sword.

I was looking at doing something like this:

filtered = filter_deck(deck, 'mace')

def filter_deck(self, deck, filt):
        return [{k:v for (k,v) in deck.items() if filt in k}]

and return:

filtered = [{
             'name': 'john',
             'lvl': 23,
             'items': ['sword', 'mace', 'health_potion']}]

I am not sure how to filter either a specific item like k:v or k:[v1,v2,v3] when I do not know if it is a single value, or a list of values, or how to filter multiple values.

I am not sure how I can filter character's with multiple keys. Say that I want to sort out characters that are lvl 23, or have items['sword'] or items['mace']. How would I have it sort in a way filter_cards(deck, ['lvl'=23, 'items'=['sword','mace'])

So if any character is lvl 23, or carries a mace or a sword, they are on that list.

like image 536
Drew Avatar asked Sep 10 '15 07:09

Drew


People also ask

How do I filter a dictionary by value?

You can use the same basic idea, using filter() + lambda + dict() , to filter a dictionary by value.

How do you filter elements in a dictionary?

Filter a Dictionary by values in Python using filter() filter() function iterates above all the elements in passed dict and filter elements based on condition passed as callback.

How do I filter a dictionary list in Python?

Solution: Use list comprehension [x for x in lst if condition(x)] to create a new list of dictionaries that meet the condition. All dictionaries in lst that don't meet the condition are filtered out. You can define your own condition on list element x .

How do you select a value from a dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.


1 Answers

Your deck is a list (of dictionaries) , it does not have .items() . so trying to do - deck.items() would fail.

Also the syntax -

filter_cards(deck, ['lvl'=23, 'items'=['sword','mace'])

is invalid , You should use a dictionary as the second element. Example -

filter_cards(deck, {'lvl':23, 'items':['sword','mace']})

You should use filter() built-in function, with a function that returns True, if the dictionary contains one of the values. Example -

def filter_func(dic, filterdic):
    for k,v in filterdic.items():
        if k == 'items':
            if any(elemv in dic[k] for elemv in v):
                return True
        elif v == dic[k]:
            return True
    return False

def filter_cards(deck, filterdic):
    return list(filter(lambda dic, filterdic=filterdic: filter_func(dic, filterdic) , deck))

Demo -

>>> deck = [{
...          'name': 'drew',
...          'lvl': 23,
...          'items': ['sword', 'axe', 'mana_potion']},{
...          'name': 'john',
...          'lvl': 23,
...          'items': ['sword', 'mace', 'health_potion']},{
...          'name': 'somethingelse',
...          'lvl': 10,
...          'items': ['health_potion']}]
>>>
>>>
>>> filter_cards(deck, {'lvl':23, 'items':['sword','mace']})
[{'lvl': 23, 'items': ['sword', 'axe', 'mana_potion'], 'name': 'drew'}, {'lvl': 23, 'items': ['sword', 'mace', 'health_potion'], 'name': 'john'}]
like image 97
Anand S Kumar Avatar answered Sep 25 '22 17:09

Anand S Kumar