Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to extract subset of key-value pairs from Python dictionary object?

How to extract subset of key-value pairs from Python dictionary object?                                     


1 Answer
Jayashree

Use dictionary comprehension technique.

We have dictionary object having name and percentage of students

>>> marks = {
'Ravi': 45.23,
'Amar': 62.78,
'Ishan': 20.55,
'Hema': 67.20,
'Balu': 90.75
}

To obtain dictionary of name and marks of students with percentage>50

>>> passed = { key:value for key, value in marks.items() if value > 50 }
>>> passed
{'Amar': 62.78, 'Hema': 67.2, 'Balu': 90.75}

To obtain subset of given names

>>> names = { 'Amar', 'Hema', 'Balu' }
>>> lst = { key:value for key,value in marks.items() if key in names}
>>> lst
{'Amar': 62.78, 'Hema': 67.2, 'Balu': 90.75}
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.