5
def parse_urls(weeks_urls):
    for wkey in weeks_urls.keys():
        results=urllib2.urlopen(weeks_urls[wkey])
        lines = list(csv.reader(results))
        lines=clean_lines(lines)
        week_dict=dict.fromkeys(lines[i][1] for i in range(len(lines)))
        fare_data=list((lines[i][1:]) for i in range(3,len(lines)))
        fare_data=get_fare_data(fare_data)
        n=3
        for station in week_dict: .....
.......

when I use dict.fromkeys( ) to produce a dict from a list of strings, it automatically sorts them, producing a dict with the strings in alphabetical order. I need to preserve the original order of the string. Is there a way to do this?

grateful for any help here

thanks!

weberc2
  • 7,423
  • 4
  • 41
  • 57
user1799242
  • 495
  • 3
  • 9
  • 12

2 Answers2

7

it automatically sorts them, producing a dict with the strings in alphabetical order

This isn't quite correct. Python's standard dict is unordered, meaning it is permitted to reorder the items as it pleases. You therefore can't rely on the keys appearing in any particular order (nor on the order staying the same across insertions/deletions).

To preserve insertion order, you could use collections.OrderedDict:

In [6]: l = [1, 2, 20, 5, 10]

In [7]: list(dict.fromkeys(l).keys())
Out[7]: [1, 2, 10, 20, 5]

In [8]: list(collections.OrderedDict.fromkeys(l).keys())
Out[8]: [1, 2, 20, 5, 10]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

Python dictionaries are "unordered" -- The order that the items are yielded in your dictionary is implementation (and insertion order) dependent and can appear almost random at times or nicely sorted at other times (apparently). For Cpython, here's some additional information for the interested reader.

You could use a collections.OrderedDict instead (which remembers insertion order). OrderedDict was added in python2.7, for earlier versions there is an ActiveState recipe that is linked in the python official documentation.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696