Python: Creating a new dictionary while switching keys and values
Question: If I am given a dictionary that has student names as keys and the subjects
they're proficient in as a set of strings, how would I go about creating a new
dictionary that would have the subjects as keys and everybody who's proficient
in those subjects in a set?

Sorry, this is my first time asking a question here, so I'm not quite sure how
to include snippets of functions.


Answer: Use a
[defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
making each of the subjects/values in each set a key and append/add each
student to a list/set as values.

    
    
    s = {'Sherman':{'calculus', 'english'},
     'Tyler': {'computers','history'},
    'Kevin': {'chemistry','PE','geometry'},
    'Joe': {'calculus','computers'},
    'Bryan': {'nothing'},
    'Steven': {'biology','research', 'algebra'}}
    
    from collections import defaultdict
    d = defaultdict(list)
    for k,v in s.items(): # iterate over key/value tuples.
        for sub in v: # get each subject in the set/value
            d[sub].append(k) # add the students to a list and and make each subject a key
    print(d)
    
     defaultdict(<type 'list'>, {'calculus': ['Sherman', 'Joe'], 'biology': ['Steven'], 'algebra': ['Steven'], 'geometry': ['Kevin'], 'computers': ['Tyler', 'Joe'], 'research': ['Steven'], 'english': ['Sherman'], 'nothing': ['Bryan'], 'chemistry': ['Kevin'], 'PE': ['Kevin'], 'history': ['Tyler']})
    

If you want sets as values use defaultdict(set) and .add instead of append:

    
    
    from collections import defaultdict
    
    d = defaultdict(set)
    for k,v in s.items():
        for sub in v:
            d[sub].add(k)
    print(d)
     defaultdict(<type 'set'>, {'calculus': set(['Sherman', 'Joe']), 'biology': set(['Steven']), 'algebra': set(['Steven']), 'geometry': set(['Kevin']), 'computers': set(['Tyler', 'Joe']), 'research': set(['Steven']), 'english': set(['Sherman']), 'nothing': set(['Bryan']), 'chemistry': set(['Kevin']), 'PE': set(['Kevin']), 'history': set(['Tyler'])})
    

Using a defaultdict means if the key does not exist in the dict it will be
added and the value appended or just appended if it does already exist, you
can use dict.setdefault but a defaultdict is more efficient.

