Python Dictionary Iteration

Write a list comprehension that returns all the pairs in a dictionary whose associated values are greater than zero.

Suppose the dictionary is -

{'English': 11, 'Aptitude': -3, 'Reasoning': 10, 'GK': -2}

Solution

Python has predefined iteritems() method that returns an iterator over the dictionary’s (key, value) pairs.

Syntax of Python iteritems()
dictionary.iteritems()

This return the iterator over the dictionary's key value pairs.

This is the following solution to return all the pairs in a dictionary whose associated values are greater than zero.

dict = {'English': 11, 'Aptitude': -3, 'Reasoning': 10, 'GK': -2}
for x in dict.iteritems():
    if x[1] > 0:
        print x

Output of the above code
Python Dictionary Iteration'


Related Articles

Python program for Prime Number
Odd Even Program in Python
Python program to convert Celsius to Fahrenheit
Python Convert XML to CSV
Python Text to Speech
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml




Read more articles


General Knowledge



Learn Popular Language