Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - How to make a dictionary retain its sort order?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...