如何使字典保留其排序顺序? [英] How to make a dictionary retain its sort order?
本文介绍了如何使字典保留其排序顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
self.lst:
如果i中的单词:
如果单词总数:
总计[word] + = 1
else:
total [word] = 1
final = sorted(total,reverse = True)
返回总额
这将返回
{'气候':10,'生态系统':1,'能量' :1,'world':2,'可再生':2,'native':2}
我想让这本字典回到一个顺序的字典。你如何排序并返回一个字典?
解决方案
有序字典会让你得到你所需要的
从集合导入OrderedDict
如果要按字典顺序排列您的项目,请执行以下
d1 = {'气候':10, 生态系统:1,能源:6,人:1,世界:2,可再生:2,本地:2}
od = OrderedDict(sorted(d1.items ),key = lambda t:t [0]))
od
:
OrderedDict([('climate',10),
生态系统,1),
('能量',6),
('人类',1),
('native',2),
,2),
('world',2)])
如果你想指定你想要你的字典哪个顺序,th将它们存储为元组,并按照该顺序存储它们。
t1 = [('气候',10),('生态系统''1',''''''''''''''''''''''''''''''''''''' = orderered()
for(key,value)在t1中:
od [key] = value
od
现在
OrderedDict([('气候',10),
('生态系统',1),
('能量',6),
('人类',1),
('world',2),
('可再生',2),
('native',2)])
在使用中,它就像一个正常的字典,但内部的内容是指定的。
def positive(self):
total = {}
final = {}
for word in envir:
for i in self.lst:
if word in i:
if word in total:
total[word] += 1
else:
total[word] = 1
final = sorted(total, reverse = True)
return total
This returns
{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
I want to get this dictionary back to a dictionary that is in order. How do you I sort it and return a dictionary?
解决方案
An ordered dictionary would get you what you need
from collections import OrderedDict
If you want to order your items in lexicographic order, then do the following
d1 = {'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
od = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
Contents of od
:
OrderedDict([('climate', 10),
('ecosystem', 1),
('energy', 6),
('human', 1),
('native', 2),
('renewable', 2),
('world', 2)])
If you want to specify exactly which order you want your dictionary, then store them as tuples and store them in that order.
t1 = [('climate',10), ('ecosystem', 1), ('energy',6), ('human', 1), ('world', 2), ('renewable', 2), ('native', 2)]
od = OrderedDict()
for (key, value) in t1:
od[key] = value
od
is now
OrderedDict([('climate', 10),
('ecosystem', 1),
('energy', 6),
('human', 1),
('world', 2),
('renewable', 2),
('native', 2)])
In use, it is just like a normal dictionary, but with its internal contents' order specified.
这篇关于如何使字典保留其排序顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文