Skip to content

Instantly share code, notes, and snippets.

@woodphil
Created March 21, 2016 20:06
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 woodphil/af6c079f444348eba7c5 to your computer and use it in GitHub Desktop.
Save woodphil/af6c079f444348eba7c5 to your computer and use it in GitHub Desktop.
pythonic dictionary inversion
# 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