0

I'm retrieving data from firebase as a list of dictionary. When I printed the list, it's not in the same order.

For example:

print(list(mydictionary.keys())[0])

This 0 element is always different, print is giving different outputs. I want to print with the same order in the database or make it the same when I took the data first as a list. Is it possible?

JaneDo
  • 1
  • 1
  • 2
  • Dict cannot assure you the order. How do you exactly get the data from firebase? Try storing keys in list while you getting the data from firebase – Ziya ERKOC Jul 13 '17 at 10:26

3 Answers3

0

I think what you want is the OrderedDict object, which preserves the order of keys as they are added. In python2.7+ this is part of the collections module:

>>> from collections import OrderedDict
>>> a = OrderedDict()
>>> a['blah'] = 4
>>> a['other'] = 5
>>> a['another'] = 6
>>> print(a)
OrderedDict([('blah', 4), ('other', 5), ('another', 6)])
>>> print(dict(a))
{'another': 6, 'blah': 4, 'other': 5}

I have no experience with firebase, so this answer could be unhelpful in this specific usage.

Duncan Macleod
  • 1,045
  • 11
  • 21
0

If you want to preserve order, use OrderedDict

from collections import OrderedDict

keys = list("1234")
values = ["one", "two", "three", "four"]

order_preserving_dict = OrderedDict(zip(keys, values))

As to why the dictionary is not preserving order, I can explain, but its better you take a look at Why is the order in dictionaries and sets arbitrary?

RinkyPinku
  • 410
  • 3
  • 20
0

Use the function sorted()

s = {0:1,h:t,1:1,10:2,2:1} for key,val in sorted(s.items()): print key, val

or in your case

print(sorted(list(mydictionary.keys())[0]))

Tobias Møller
  • 64
  • 1
  • 1
  • 8