2

I have the below strings in a list and have been able to create a dictionary using the list as key in the dictionary and assigning default of ''. When I print, I see the dictionary is created in reverse order for string in list. Why does this happen and how to correct it. Is there a reverse syntax required ?

a = ['hello','bye','tc','iam']
created_dict = dict((bl,'') for bl in a)
print created_dict # {'iam': '', 'bye': '', 'hello': '', 'tc': ''}

What needs to be changed to get the below result.

expected result : {'hello': '', 'bye': '', 'tc': '', 'iam': ''}

It maintains the order when numbers are used in list

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Are you sure you need it to be ordered? If so, a dictionary is not the data structure you want. A list or linkedlist would probably be better. – Eugene K Oct 11 '15 at 03:29

1 Answers1

2

Regular dictionaries in Python have no notion of key order, you need an OrderedDict

from collections import OrderedDict
o = OrderedDict.fromkeys(['hello', 'bye', 'tc', 'iam'], '')                    
repr(o)
OrderedDict([('hello', ''), ('bye', ''), ('tc', ''), ('iam', '')])
iruvar
  • 22,736
  • 7
  • 53
  • 82
  • "you need an OrderedDict" - more likely, order is unnecessary, and using an OrderedDict will just encourage unnecessary headaches about trying to maintain a specific order in the face of dict modifications. – user2357112 Oct 11 '15 at 03:25