2

for example, let's say I have this dictionary:

Dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

I want to get a list like this: ['Name', 'Age', 'Class'] and not in other order

Caterina
  • 775
  • 9
  • 26
  • By writing `['Name', 'Age', 'Class']`. – Stefan Pochmann Jun 30 '17 at 06:05
  • 1
    What's wrong with Dict.keys()? – Zeokav Jun 30 '17 at 06:06
  • This was just an example. The point is that in the problem I am working on I don't know the names of any of the keys – Caterina Jun 30 '17 at 06:07
  • instead of `Dict` if you go with `collections.OrderedDict` it can give always same order. – Hara Jun 30 '17 at 06:07
  • 1
    Dictionaries aren't ordered data structures. If the order matters to you, use a `collections.OrderedDict` instead. – jonrsharpe Jun 30 '17 at 06:08
  • Dict.keys() may return the keys in a different order. Maybe not for this example. But in general. Is not exactly as in the order it appears in the dict – Caterina Jun 30 '17 at 06:09
  • @Caterina I think you should have a look a at the available ordered version of a dictionary, you can read this in here: [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict). @StefanPochmann why even bother commenting this? It was obviously just an example. – Vinícius Figueiredo Jun 30 '17 at 06:10
  • Is there a way to convert an ordinary Dict to an Ordered Dict? – Caterina Jun 30 '17 at 06:11
  • @Caterina I doubt it. I believe using a tuple to store the data first works. Since the normal dict does not remember the order of elements, even if you try to convert it to an orderedDict, the order will be wrong. – hridayns Jun 30 '17 at 06:14
  • You should never be relying on the iteration order of `dict` - if `dict.keys()` doesn't return the same order as `dict` itself that's a *feature*. – dimo414 Jun 30 '17 at 06:31

2 Answers2

2

Try from this source: Key Order in Python Dictionaries

OrderedDict([('a', 1), ('b', 2), ('c', 3)])

Sadly, OrderedDict({'a': 1, 'b':2, 'c':3}) won't work because The {} has already forgotten order of the elements.

Your code would be:

Dict = OrderedDict([('Name', 'Zara'), ('Age', 7), ('Class', 'First)])
hridayns
  • 697
  • 8
  • 16
0

Dictionaries are inherently unordered; the order of the keys is not defined. There's no way to recover the order that you wrote them down in.

If you need an ordered version of a dictionary, look into OrderedDict from collections.

perigon
  • 2,160
  • 11
  • 16