Franco
Franco

Reputation: 39

How to select a sub-dictionary given a condition

mydict = {'a': {'name': 'Marco', 'gender': 'm', 'age': 38, 'info': 'teacher musician'}
          'b': {'name': 'Daniela', 'gender': 'f', 'age': 28, 'info': 'student music'}
          'c': {'name': 'Maria', 'gender': 'f', 'age': 25, 'info': 'doctor dance whatever'}}

How to select the records with an age below 30 and with the words including 'music' in the 'info'? The results should be like:

newdict = {'b': {'name': 'Daniela', 'gender': 'f', 'age': 28, 'info': 'student music'}}

Upvotes: 1

Views: 1200

Answers (2)

Kasravnd
Kasravnd

Reputation: 107297

You can use the following comprehension :

>>> {d:k for d,k in mydict.items() if k['age']<30 and 'music' in k['info']}
{'b': {'info': 'student music', 'gender': 'f', 'age': 28, 'name': 'Daniela'}}

mydict.items() give you a tuple contain key ans value of dictionary at each loop , and you can chose the item that have the proper conditions !

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142176

Simplest way is to use a dict-comp:

mydict = {'a': {'name': 'Marco', 'gender': 'm', 'age': 38, 'info': 'teacher musician'},
          'b': {'name': 'Daniela', 'gender': 'f', 'age': 28, 'info': 'student music'},
          'c': {'name': 'Maria', 'gender': 'f', 'age': 25, 'info': 'doctor dance whatever'}}

new_dict = {k:v for k,v in mydict.iteritems() if v['age'] < 30 and 'music' in v['info'].split()}
# {'b': {'info': 'student music', 'gender': 'f', 'age': 28, 'name': 'Daniela'}}

Upvotes: 6

Related Questions