Skip to content

Instantly share code, notes, and snippets.

@leveled
Last active February 22, 2021 00:39
Show Gist options
  • Save leveled/9a35b884b45ec7349dec18142537e793 to your computer and use it in GitHub Desktop.
Save leveled/9a35b884b45ec7349dec18142537e793 to your computer and use it in GitHub Desktop.
Dictionary comprehensions in Python cheatsheet
#Double each value in a dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
#If/else in dictionary comprehension
dict1_tripleCond = {k:('even' if v%2==0 else 'odd') for (k,v) in dict1.items()}
#Nested dict
nested_dict = {'first':{'a':1}, 'second':{'b':2}}
float_dict = {outer_k: {float(inner_v) for (inner_k, inner_v) in outer_v.items()} for (outer_k, outer_v) in nested_dict.items()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment