- #1
ver_mathstats
- 260
- 21
- Homework Statement
- Given a dictionary d, create a new dictionary that reverses the keys and values of d. Thus, the keys of d become the values of the new dictionary and the values of d become the keys of the new dictionary. If there is a common value for several keys in d then only the last key becomes a value in the new dictionary. Perform the following test case: when d is {1:7, 2:5, 3:7, 4:16, 5:25, 6:5, 9:7} your code should produce the dictionary {7:9, 5:6, 16:4, 25:5}.
- Relevant Equations
- python
Python:
d={1:7,2:5,3:7,4:16,5:25,6:5,9:7}
reverse_d={}
for a, b in d.items():
reverse_d[b] = reverse_d.get(b,a)
print(reverse_d)
I ended up reversing the keys in the dictionary, so I have the 7, 5, 16, and 25 correct. I am just struggling with making the last key become a new value in the dictionary. Overall my code prints {7:1, 5:2, 16:4, 25:5}, I just do not know how to get the last element. Could I please have help with that? Thank you.