This question already has an answer here:
I am using this to produce a plot of % of names starting with a certain letter over a span of years. When plotting (and printing) my diction (letter_d) the keys are disordered rather than being sequential like how they are added to the dict. Is there a way to fix this, I believe I am adding them to the dict in a sequential order. If not is there a way I can create connect the dots of my scatter plot in order to simulate the correct line plot?
import csv
import matplotlib.pyplot as plt
start = 1880
stop = 1890
x = []
years = range(start, stop +1)
print years
letter_d = {}
year_d = {}
alphabet = ['Z']#,'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
for i in alphabet:
letter_d[i] = 0
for year in years:
filename = 'yob' + str(year) + '.txt'
z = open(filename)
year_d[int(year)] = 0
letter_d[i] = year_d
c = 0
d = 0
for line in z:
y = line.strip().split(',')
y.remove(y[1])
c += int(y[1])
if i in y[0]:
d += int(y[1])
year_d[year] = float(d)/float(c)
#x.append(y)
#print year_d
print year_d.keys()
plt.plot(year_d.keys(), year_d.values())
plt.show()
Python dictionaries are always unordered.
In your case, you don't need a dictionary at all. Use two lists; one is the years
list you already produced from a range, the other for the calculated values:
year_values = []
for year in years:
# ...
year_values.append(float(d)/float(c))
plt.plot(years, year_values)
As it was said dictionaries are unordered. To keep your code, there is a way to display your plot sorted. Sorting dictionary keys.
Look
if __name__ == "__main__":
year_d = {"5": 'b', "3": 'c', "4": 'z', "1":'a'}
print year_d.keys()
keys = map(int, year_d.keys())
keys = map(keys.sort(), keys)
print keys
original: ['1', '3', '5', '4'] sorted: [1, 3, 4, 5]
来源:https://stackoverflow.com/questions/21651067/why-does-my-python-dict-become-unordered