File to dictionary alphabetical loss

52 Views Asked by At

So, right now I have a text filed with alternating rows of state name abbreviations and their respective populations. The file is sorted alphabetically, with AK being the first line and so on. I am trying to put all of these into a dictionary, with the abbreviation being the key and the population being the value. This is my code so far.

for line in f1:
    key, val = line.split()
    population[key] = int(val)
    fontsize.append(int(val))

However, when I try to print my dictionary called population, I get

{'WA': 5894121, 'DE': 783600, 'DC': 572059, 'WI': 5363675, 'WV': 1808344, 'HI': 1211537, 'FL': 15982378, etc.}

Is there a reason why it is it alphabetical anymore?

1

There are 1 best solutions below

0
On

Python dicts do not preserve order. You want to use an OrderedDict from the collections module. OrderedDicts preserve key order in the order they were added.

The order of dict keys is consistent but not necessarily anything useful.

https://docs.python.org/2/library/collections.html#collections.OrderedDict