Created
March 21, 2016 20:06
-
-
Save woodphil/af6c079f444348eba7c5 to your computer and use it in GitHub Desktop.
pythonic dictionary inversion
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
# example: dictionary that has students as keys and within each entry has a list of teachers that teach that student | |
# this snippet will use that dictionary to create a dictionary with teachers as keys and within those entires have a list | |
# of students taught by that teacher | |
for e in dic.keys(): | |
for d in dic[e]: | |
if not data.get(d): | |
data[d] = set() | |
data[d].add(e) | |
#simplified | |
for e,sub_dic in dic.iteritems(): | |
for d in sub_dic: | |
data.setdefault(d, set()) | |
data[d].add(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment