Skip to content

Instantly share code, notes, and snippets.

@ducin
Created July 10, 2013 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducin/5970372 to your computer and use it in GitHub Desktop.
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
# 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'])])
# 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