为什么我的python dict变得无序? [英] Why does my python dict become unordered?

查看:441
本文介绍了为什么我的python dict变得无序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个产品,在多年的时间内,以特定字母开头的名字的百分比。当绘制(和打印)我的diction(letter_d)时,键是无序的,而不是像它们被添加到dict中的顺序。有没有办法解决这个问题,我相信我会按顺序将它们添加到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字典总是无序。

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)

这篇关于为什么我的python dict变得无序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆