-1

I know this may be a simple question but I'm having trouble reversing my dictionary. All the solutions I've seen haven't been working for me. I have a dictionary where the keys are strings and the values are either None or type int. I want to reverse the order so the last (key, value) pair is first and vice versa.

For example:

d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD: None}

I want to reverse the dictionary to:

reversed_d = {"pointD": None, "pointC": None, "pointB": 140, "pointA": 100}

I've tried sorted(d.items(), reverse=True) and reversed(sorted(d.items())) but I got an error of:

TypeError: '<' not supported between instances of 'int' and 'str' 
David
  • 153
  • 1
  • 14
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value). You may first need to iterate through your dictionary and confirm the type and convert None to np.nan. – Trenton McKinney May 31 '20 at 02:23
  • What is the next step after sorting? Order of dictionary is less important. – Austin May 31 '20 at 02:25
  • Hey Austin, After sorting I want to loop over the keys and values and update them depending on specific events. I already looped over them in its current order but now I need to loop over them reversed. – David May 31 '20 at 02:29
  • Hey Trenton, I attempted the code {k:v for k, v in sorted(d.items(), key=lambda item: item[1])} but I got an error of TypeError: '<' not supported between instances of 'dict' and 'dict' – David May 31 '20 at 02:32

2 Answers2

1

You could do it this way.

Loop =>

for k,v in reversed(list(d.items())):

or just

reversed_d = reversed(list(d.items()))
Sonikk
  • 39
  • 5
  • The for loop works only when I print k and v. When I try to store them into a dict it returns the memory address instead of its inputs. Likewise in your example: reversed_d returns a memory address for me. Ex: or – David May 31 '20 at 02:57
  • @David you just need to cast it to an dict like => ``` reversed_d = dict(reversed(list(d.items()))) ``` – Sonikk May 31 '20 at 12:03
0

since dictionaries are ordered by insertion order of the keys (since python 3.6, guaranteed since python 3.7), you can reverse the keys:

d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD": None}

for k in reversed(d):
    print(k)

From there, you can build a new dictionary by inserting key values in the reversed order, or create a generator to access the (Key, value) pairs in that order.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80