如何按Python在Python中排序字典 [英] How to sort dictionaries by keys in Python

查看:122
本文介绍了如何按Python在Python中排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我如何排序:

Can anyone tell me how I can sort this:

{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}

into

{'a': [1, 2, 3], 'b': ['blah', 'bhasdf', 'asdf'], 'c': ['one', 'two'],'d': ['asdf', 'wer', 'asdf', 'zxcv']}


谢谢!

更新1,代码示例:

所以我在做语言学。一篇文章被分解为存储在数据库中并具有各种属性(包括para ID和句子ID)的单词。任务:尝试重建原始文本。

So I am doing linguistics. One article is broken down to words that are stored in a database and have all kinds of properties including para ID and sentence ID. The task: trying to rebuild the original text.

从DB获取500个连续的单词

Get 500 consecutive words from DB

words = Words.objects.all()[wordId:wordId+500]
# I first create paragraphs, through which I can loop later in my django template,
# and in each para will be a list of words (also dictionaries). 
# So i am trying to get a dictionary with values that are lists of dictionaries. 
# 'pp' i make just for shorthanding a long-named variable.
paras={}
para_high = para_low =  words[0].belongs_to_paragraph
for w in words:
    last_word = w
    pp = w.belongs_to_paragraph
    if pp >para_high:
        para_high = pp
    if pp < para_low:
        para_low = pp
    if pp in paras:
        paras[pp].append(w)
    else:
        list = [w]
        paras[pp] = list
# Since there are blank lines between paragraphs, in rebuilding the text as it 
    #  looked originally, I need to insert blank lines. 
    # Since i have the ID's of the paragraphs and they go somewhat like that: 1,3,4,8,9 
    #(the gaps between 1 & 3 and 4 & 8 i have to fill in with something else, 
    # which is why i had para_low and para_high to loop the range. 
isbr = True
for i in range(para_low, para_high+1):
    if i in paras:
        isbr = True
    else:
        if isbr:
            paras[i]=['break']
            isbr = False
        else:
            paras[i]=[]

但是,在这一点上,如果我尝试循环dict并重建文本,一些后来的id'd段落在之前的段落之前,而不是这样做。

At this point, however, if I try to loop the dict and rebuild the text, some later id'd paragraphs come before previous ones, and that just doesn't do it.

更新2,循环代码:

        {% for k,v in wording.iteritems()  %}
        {% if v[0] == 'break' %}
        <br/>
        {% else %}
        </div><div class="p">{% for word in v %}{% if word.special==0%} {% endif %}<span class="word {% if word.special == 0%}clickable{% endif%}" wid="{{word.id}}" special="{{word.special}}" somethingElse={{word.somethingElse}}>{{ word.word }}</span>{% endfor %}
        {% endif %}
    {% endfor %}


推荐答案

Dicts没有订单

您可以调用排序,但这只是给您一个按键列表:

You can call sorted but this just gives you a sorted list of the keys:

>>> sorted(d)
['a', 'b', 'c', 'd']

您可以将其视为一个迭代,并对键值元组进行排序,但是您只需要一个元组列表。这不一定是一个dict。

You can treat it as an iterable and sort the key-value tuples, but then you've just got a list of tuples. That's not the same as a dict.

>>> sorted(d.items())
[
 ('a', [1, 2, 3]),
 ('b', ['blah', 'bhasdf', 'asdf']),
 ('c', ['one', 'two']),
 ('d', ['asdf', 'wer', 'asdf', 'zxcv'])
]

如果您使用的是Python 2.7或更高版本,您还可以考虑使用 OrderedDict

If you are using Python 2.7 or newer you could also consider using an OrderedDict.


dict子类记住添加的订单条目

dict subclass that remembers the order entries were added

例如:

>>> d = collections.OrderedDict(sorted(d.items()))
>>> for k, v in d.items():
>>>     print k, v




a [1, 2, 3]
b ['blah', 'bhasdf', 'asdf']
c ['one', 'two']
d ['asdf', 'wer', 'asdf', 'zxcv']

这篇关于如何按Python在Python中排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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