Quantcast
Channel: Forums - Python
Viewing all articles
Browse latest Browse all 2485

Is it possible to sort a text file before creatinga dictionary?

$
0
0
I am using a txt file to create a dictionary. However the dictionary is not sorted according to the txt file no matter the sequence of values in the txt file. Is there a way to sort the file or to sort the dictionary according alphabetically ascending (A to Z) or in the order it is in the file? Thanks!

Code:

file = open('D:\\ArcGISDATA\\SARS\\OfficeDomain_list.txt', 'r')

foresterdomaintxt = {}

for line in file.readlines():

        x = line.split(",")
        a = x[0]
        b = x[1]
        bstrip =x[1].strip('\n')
        foresterdomaintxt[a]=bstrip
print foresterdomaintxt

Here is the file:

Code:

Temple,TE
San Angelo,SG
San Augustine,ST
Weslaco,WE

And here is what I get, no matter the order of items in the file:

{'Weslaco': 'WE', 'San Augustine': 'ST', 'Temple': 'TE', 'San Angelo': 'SG'}

Viewing all articles
Browse latest Browse all 2485

Trending Articles