Method # 1: Using Dictation
# Python code for demonstration # return the filtered dictionary # by certain criteria from six import iteritems # Initializing dictionary ini_dict = { ’a’ : 1 , ’ b’ : - 2 , ’c’ : - 3 , ’d’ : 7 , ’e’ : 0 } # print the original dictionary print ( "initial lists" , str (ini_dict)) # filter the dictionary so that no values exceed 0 result = dict ((k, v) for k, v in ini_dict.items () if v" = 0 ) print ( "resultant dictionary:" , str (result)) |
Output:
initial lists {’a’: 1,’ c’: -3, ’d’: 7,’ b’: -2, ’e’: 0} resultant dictionary: {’a’: 1,’ d’: 7, ’e’: 0}
Method # 2: Using lambda and filter
# Python code for demo # return the filtered dictionary from six import iteritems # Initializing dictionary ini_dict = { ’a’ : 1 , ’b’ : - 2 , ’ c’ : - 3 , ’d’ : 7 , ’e’ : 0 } # print the source dictionary print ( "initial lists" , str (ini_dict) ) # filter the dictionary so that no values exceed 0 result = dict ( filter ( lambda x: x [ 1 ]" = 0.0 , ini_dict.items ())) result cod e> = dict (result) print ( "resultant dictionary:" , str (result) ) |
Exit:
initial lists {’c’: -3,’ d’: 7, ’e’: 0,’ a’: 1, ’b’: -2} resultant dictionary: {’ e’: 0, ’a’: 1,’ d’: 7}