Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17477

Inverting a dictionary in Python with lists as values [duplicate]

$
0
0

I'm a little new to python and programming in general. I'm having some difficulty inverting a dictionary in the way that I want. I have a dicitonary that is a has three names as keys and they each have three courses they are taking, the values. The values are in a list. The goal is to invert the dict so that courses are the keys and the students are the values. The catch is, I deliberately had some overlap in the courses. Here's the code:

students = {'jim': ['ENGL1102', 'MATH1201', 'CS1102',],'sally': ['CS1103', 'UNIV1001','MATH1201'],'sam': ['MATH1201', 'UNIV1001', 'CS1102',],            }

And this is the approximate output I'm trying to get:

{'ENGL1102':['jim'],'MATH1201': ['jim,'sally', 'sam' ],'CS1102': ['jim'],'CS1103': ['sally'],'UNIV1001': ['sam', 'sally'],'CS1102': ['sam'],}

As you can see, we have new dict with only one listing of each course, but the list values have all the students names who are taking that course.

The followig is the main approach I've tried. I beleive this is a dicitonary comprehention, but I could be wrong. It invert the dict, but really only does that.

invert = {v: k for k, v in students.items()}print(invert)`

The output I get is inverted, but not what I want and not really useful:

{('ENGL1102', 'MATH1201', 'CS1102'): 'jim', ('CS1103', 'UNIV1001', 'MATH1201'): 'sally', ('MATH1201', 'UNIV1001', 'CS1102'): 'sam'}

So what would be the best and most pythonic way to get the intended output? I should also add that I had to change the lists-values to tuples in order for the program to run. Is there a way around this?

Thanks!


Viewing all articles
Browse latest Browse all 17477

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>