-1

Hello I am having trouble making a function that reverses any dictionary given to it but without any special libraries. For example

D = {one:uno, two:dos}

would return that dictionary as D = {uno:one, dos:two}

I am asking the reverse order for both the key and value not just key, this is very different

kid prog
  • 35
  • 1
  • 6

1 Answers1

2

Try this:

result = dict((v,k) for k,v in d.items())

Example:

d = {'one':'uno', 'two':'dos'}
result = dict((v,k) for k,v in d.items())
print(result) # prints - {'uno': 'one', 'dos': 'two'}

What is happening here?

  • (v,k) for k,v in d.items() - You first iterate over all the (key, value) pairs in the dictionary and create tuples of (value, key).
  • Then you call dict() to create dictionary from the tuples.
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161