Created
July 10, 2013 21:12
-
-
Save ducin/5970372 to your computer and use it in GitHub Desktop.
summing up python dictionary values: add all values, where type='+' should be added, type='-' should be subtracted and other type should be ignored
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# define entries | |
entries = [{'type': '+', 'value': 9},\ | |
{'type': '+', 'value': 12.3},\ | |
{'type': '-', 'value': 4},\ | |
{'type': '+', 'value': 0.89},\ | |
{'type': '-', 'value': 2.65},\ | |
{'type': '-', 'value': 14.3},\ | |
{'type': '+', 'value': 6.8},\ | |
{'type': 'unknown', 'value': 200}] | |
# use functional dictionary as a switch-case statement replacement | |
def add(arg): | |
return arg | |
def sub(arg): | |
return -arg | |
functions = {"+": add, "-": sub} | |
print sum([functions[x['type']](x['value']) for x in entries if functions.has_key(x['type'])]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# define entries | |
entries = [{'type': '+', 'value': 9},\ | |
{'type': '+', 'value': 12.3},\ | |
{'type': '-', 'value': 4},\ | |
{'type': '+', 'value': 0.89},\ | |
{'type': '-', 'value': 2.65},\ | |
{'type': '-', 'value': 14.3},\ | |
{'type': '+', 'value': 6.8},\ | |
{'type': 'unknown', 'value': 200}] | |
# use nested ternary operator (X if Y else Z) | |
print sum([x['value'] if x['type'] == '+' else (-x['value'] if x['type'] == '-' else 0) for x in entries]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment