1

I have this defaultdict and a string variable:

my_dict = defaultdict(<class 'str'>, {2: 'bear', 3: 'fish', 4: 'dog', 5: 'goat'})

str_match = "goat"

and I would like to pop the key in my_dict which has the same value as str_match, and insert it at the front. Something like this:

my_dict = defaultdict(<class 'str'>, {5: 'goat', 2: 'bear', 3: 'fish', 4: 'dog'})

So far I have:

for key, value in list(my_dict.items()):
    if value == str_match:
        my_dict.pop(key)

Is there a way I can accomplish this?

Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • 5
    What do you mean _at the front_? Dictionaries **are not** ordered. – Łukasz Rogalski May 12 '16 at 11:19
  • Not with a dictionary - 'at the front' is meaningless as dictionaries are not ordered. The pair 'at the front' may not be in the same place the next time you access the dictionary. – nekomatic May 12 '16 at 11:21
  • Python 3.2 introduced a `move_to_end` method that lets you move a key to the start or end of the sequence of keys. (Keys are otherwise ordered by their insertion order; they cannot be arbitrarily sorted.) – chepner May 12 '16 at 11:36

1 Answers1

2

You can use the OrderedDict in python 2.7 or above. The link of Documentation is: https://docs.python.org/2/library/collections.html#collections.OrderedDict