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
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
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)])
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.