Skip to content Skip to sidebar Skip to footer

Filtering Nested Dictionaries

So I have this dictionary: Filme = {'1': {'Titel': 20, 'Jahr': 2, 'Wertung': 6, 'Preis': 50, 'Schauspielern': ['a', 'b', 'c']}, '2': {'Titel': 30, 'Jahr': 3, 'Wertung': 7,

Solution 1:

You can just use a dictionary comprehension over the Filme.items():

In [2]: {k:v for k,v in Filme.items() if v['Wertung'] >= 7}
Out[2]:
{'2': {'Jahr': 3,
  'Preis': 70,
  'Schauspielern': [''],
  'Titel': 30,
  'Wertung': 7},
 '4': {'Jahr': 3,
  'Preis': 20,
  'Schauspielern': [''],
  'Titel': 5,
  'Wertung': 9},
 '5': {'Jahr': 3,
  'Preis': 100,
  'Schauspielern': [''],
  'Titel': 8,
  'Wertung': 10},
 '7': {'Jahr': 3,
  'Preis': 20,
  'Schauspielern': [''],
  'Titel': 16,
  'Wertung': 9},
 '9': {'Jahr': 3,
  'Preis': 20,
  'Schauspielern': [''],
  'Titel': 90,
  'Wertung': 9}}

This is equivalent to the following:

new_dict = {}
fork,v in Filme.items():
    if v['Wertung'] >= 7:
        new_dict[k] = v

Solution 2:

Dictionary comprehension will be most straight-forward.

>>> {i:j for i,j in Filme.items() if j['Wertung'] >=7}
{'7': {'Titel': 16, 'Wertung': 9, 'Preis': 20, 'Jahr': 3, 'Schauspielern': ['']}, '5': {'Titel': 8, 'Wertung': 10, 'Preis': 100, 'Jahr': 3, 'Schauspielern': ['']}, '4': {'Titel': 5, 'Wertung': 9, 'Preis': 20, 'Jahr': 3, 'Schauspielern': ['']}, '2': {'Titel': 30, 'Wertung': 7, 'Preis': 70, 'Jahr': 3, 'Schauspielern': ['']}, '9': {'Titel': 90, 'Wertung': 9, 'Preis': 20, 'Jahr': 3, 'Schauspielern': ['']}}

If there is a chance that Wertung might be absent for any entry, you can use get() to prevent the code from failing unexpectedly.

>>> {i:j for i,j in Filme.items() if j.get('Wertung',0) >=7}

Post a Comment for "Filtering Nested Dictionaries"