I'm trying to take a dictionary of keys and values and then swap the corresponding keys and values around, from looking through previously posted questions I know you can swap keys/ values of a dictionary around using something such as:
newdict = dict((b,a) for a,b in D.items())
I am also aware that dictionaries are not ordered, so with a lengthy dictionary the each key/ value pair will not be in the same position in the new dictionary as the original dictionary.
So my question is, is there any way of swapping the first pair of items then appending to a list (so they are in order) then append to a new dictionary? Then repeat this process for the second pair of terms and so on? This may seem a stupid question but it is one that I don't understand, any help will be greatly appreciated as always. :)
For clarification here is what my current code does:
D = {1:2, 3:4, 5:6, 8:9, 20:11} #this is the input
{9: 8, 2: 1, 11: 20, 4: 3, 6: 5} #this is the output
I would ideally like the output to be:
{2:1, 4:3, 6:5, 9:8, 11:20}
As a point of reference my code is simply:
def invert():
newdict = list((b,a) for a,b in D.items())
D = {1:2, 3:4, 5:6, 8:9, 20:11}
invert()