Home > OS >  Filter python dictionary by nested value, return full items not only values?
Filter python dictionary by nested value, return full items not only values?

Time:09-12

Want to filter all the items that have a C for nested Hardware value, but return the key, and key:Value data as in the original

SomeDict= {'al':  {'Hardware': 'K', 'speed' : '100' },
'ar2':  {'Hardware': 'C', 'speed' : '' },
'ar3':  {'Hardware': 'C', 'speed' : '' }}

FilterMagic_Desired_Result-> {'ar2': {'Hardware': 'C', 'speed' : '' }, 'ar3': {'Hardware': 'C', 'speed' : '' }}

Tried double for loop but I know this is not the pythonic way and it did not return the keys like al, ar2 and ar3.

How do I get the desired result

CodePudding user response:

A dictionary comprehension like this:

SomeDict= {
  'al':  {'Hardware': 'K', 'speed' : '100' },
  'ar2':  {'Hardware': 'C', 'speed' : '' },
  'ar3':  {'Hardware': 'C', 'speed' : '' }
}

FilterMagic_Desired_Result = {k: v for k, v in SomeDict.items() if v['Hardware'] == 'C'}
print(FilterMagic_Desired_Result)

Output:

{'ar2': {'Hardware': 'C', 'speed': ''}, 'ar3': {'Hardware': 'C', 'speed': ''}}

By the way, the 'pythonic' way of doing things here would be to also name your variables without capitals, e.g:

some_dict = {
  'al':  {'Hardware': 'K', 'speed' : '100' },
  'ar2':  {'Hardware': 'C', 'speed' : '' },
  'ar3':  {'Hardware': 'C', 'speed' : '' }
}

filter_magic_desired_result = {k: v for k, v in some_dict.items() if v['Hardware'] == 'C'}
print(filter_magic_desired_result)

You want to use capitals on class names, but not on variable or function names.

CodePudding user response:

A dictionary comprehension is good in a situation like this;

FilteredDict = {k:v for k,v in SomeDict.items() if v['Hardware']=='C'}
  • Related