From this code snippet...
myItem = {
'A/A': {'id': 'AA','bool': False},
'A/B': {'id': 'AB','bool': True},
'A/C': {'id': 'AC','bool': False},
'A/D': {'id': 'AC','bool': True}
}
how do I filter myItem
so that I only get those item that has 'bool': True
in it?
I tried doing list comprehension to get ['A/B']
like so:
[item for item in myItem if item.endswith('B')]
I tried...
[item for item in myItem if item.bool==True]
but it's giving me an error:
AttributeError: 'str' object has no attribute 'bool'
All I want is to get items ['A/B', 'A/D']
by filtering 'bool': True
, but unfortunately, I don't know how to do it.
CodePudding user response:
You can reconstruct the dictionary object with comprehension, like this
myItem = {
'A/A': {'id': 'AA', 'bool': False},
'A/B': {'id': 'AB', 'bool': True},
'A/C': {'id': 'AC', 'bool': False},
'A/D': {'id': 'AC', 'bool': True}
}
print({key: value for key, value in myItem.items() if value.get('bool', False)})
might print
{
'A/B': {'bool': True, 'id': 'AB'},
'A/D': {'bool': True, 'id': 'AC'}
}
The key here is to iterate through all the key-value pairs of myItem
and filter the items based on the value dictionary's bool
key.
if value.get('bool', False)
is to ensure that if bool
is not found in the dictionary, we ignore that. So, if bool
is not present, then by default False
would be returned.
CodePudding user response:
You can use filter
to filter only items meeting a specific condition and then create a new dictionary out of them (or a list if you prefer):
dict(filter(lambda x: x[1].get('bool'), myItem.items()))
This is the result:
{'A/B': {'id': 'AB', 'bool': True}, 'A/D': {'id': 'AC', 'bool': True}}