+ 1
Inverting a dictionary with lists as values - Python Help
The function down below, invert a dictionary that has lists as values, I wanted to understand how it works ------------------------ def invert_dict(d): inverted = {} for k in d: for v in d[k]: #This Part inverted.setdefault(v, []).append(k)#This part return inverted ----------------------- This is the part that I didn't get if anyone can explain to me please, i'am beginner : ------------------ for v in d[k]: inverted.setdefault(v, []).append(k) -----------------
1 Resposta
0
I think there is no need of for loop inside for loop
inverted.setdefault(v,[]).append(k)
its a inbuild condition for inverting
.............................................................................
you can reduce for loops
def invert_dict(d):
inverted = {}
for k, v in d.iteritems():
inverted.setdefault(v, []).append(k)
return inverted
d = {###dictionary contents###}
print invert_dict(d)