为什么使用 setdefault() 乱序创建这个 python 字典? [英] Why does this python dictionary get created out of order using setdefault()?

查看:37
本文介绍了为什么使用 setdefault() 乱序创建这个 python 字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始玩 Python(VBA 背景).为什么这本词典会乱序创建?不应该是a:1、b:2...等吗?

I'm just starting to play around with Python (VBA background). Why does this dictionary get created out of order? Shouldn't it be a:1, b:2...etc.?

class Card:
def county(self):
    c = 0
    l = 0
    groupL = {}  # groupL for Loop
    for n in range(0,13):
        c += 1
        l = chr(n+97)
        groupL.setdefault(l,c)
    return groupL

pick_card = Card()
group = pick_card.county()
print group

这是输出:

{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12}

或者,它是否只是乱序打印?

or, does it just get printed out of order?

推荐答案

字典在 python 中没有顺序.换句话说,当您遍历字典时,键/项目产生"的顺序​​不是您将它们放入字典的顺序.(在不同版本的 python 上尝试你的代码,你可能会得到不同排序的输出).如果你想要一个有序的字典,你需要一个 collections.OrderedDict 直到 python 2.7 才被引入.如果您使用的是旧版本的 Python,您可以在 ActiveState 上找到等效的方法.但是,通常对项目进行排序就足够了(例如 sorted(mydict.items()).

Dictionaries have no order in python. In other words, when you iterate over a dictionary, the order that the keys/items are "yielded" is not the order that you put them into the dictionary. (Try your code on a different version of python and you're likely to get differently ordered output). If you want a dictionary that is ordered, you need a collections.OrderedDict which wasn't introduced until python 2.7. You can find equivalent recipes on ActiveState if you're using an older version of python. However, often it's good enough to just sort the items (e.g. sorted(mydict.items()).

EDIT 根据要求,OrderedDict 示例:

EDIT as requested, an OrderedDict example:

from collections import OrderedDict
groupL = OrderedDict()  # groupL for Loop
c = 0
for n in range(0,13):
    c += 1
    l = chr(n+97)
    groupL.setdefault(l,c)

print (groupL)

这篇关于为什么使用 setdefault() 乱序创建这个 python 字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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