为什么我的python dict变得无序?

编程入门 行业动态 更新时间:2024-10-24 10:25:12
本文介绍了为什么我的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变得无序?

本文发布于:2023-10-23 00:11:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   dict

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!