python字典为什么是无序的_为什么我的python dict变得无序?

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值