0

Is there are any way to determine initial_list i've build my_dict from, only by using that dictionary itself:

initial_list = [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'),
                (1,2), ('a','z'), ('aa','z')]
my_dict = dict(initial_list)

As I have found out one of the option to get initial list(but order of items in it is differs from original list) is by using zip or dict.items:

initial_list_from = zip(my_dict.keys(),my_dict.values())
print initial_list_from == initial_list #False

initial_list_from = my_dict.items()
print initial_list_from == initial_list #False

The problem with such approach is that my_dict == initial_list evaluates to false, they aren't same...

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82

1 Answers1

2

It's not possible, because dict class doesn't store order of keys it was created from.

The only way to do that is by using OrderedDict which is a dict that remembers the order that keys were first inserted.

from collections import OrderedDict

initial_list = [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'),
                    (1,2), ('a','z'), ('aa','z')]
my_dict = OrderedDict(initial_list)

initial_list_from = my_dict.items()
print initial_list_from == initial_list # True
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82