Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable automatic dict sorting with dict.fromkeys( )?

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!

like image 797
user1799242 Avatar asked Dec 11 '12 16:12

user1799242


1 Answers

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]
like image 159
NPE Avatar answered Sep 22 '22 15:09

NPE