Last active
February 22, 2021 00:39
-
-
Save leveled/9a35b884b45ec7349dec18142537e793 to your computer and use it in GitHub Desktop.
Dictionary comprehensions in Python cheatsheet
This file contains hidden or 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
#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