问题:字典中键的顺序

码:

d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()

print l

打印['a', 'c', 'b']。我不确定该方法如何keys()确定l中关键字的顺序。但是,我希望能够以“适当”的顺序检索关键字。当然,正确的顺序将创建列表['a', 'b', 'c']

Code:

d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()

print l

This prints ['a', 'c', 'b']. I’m unsure of how the method keys() determines the order of the keywords within l. However, I’d like to be able to retrive the keywords in the “proper” order. The proper order of course would create the list ['a', 'b', 'c'].


回答 0

您可以使用OrderedDict(需要Python 2.7)或更高版本。

另外,请注意,OrderedDict({'a': 1, 'b':2, 'c':3})由于dict您使用进行创建的操作{...}已经忘记了元素的顺序,因此该操作无效。相反,您想使用OrderedDict([('a', 1), ('b', 2), ('c', 3)])

如文档中所述,对于低于python 2.7的版本,可以使用配方。

You could use OrderedDict (requires Python 2.7) or higher.

Also, note that OrderedDict({'a': 1, 'b':2, 'c':3}) won’t work since the dict you create with {...} has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)]).

As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.


回答 1

Python 3.7以上

在Python 3.7.0中dict对象的插入顺序保留性质已声明为Python语言规范的正式组成部分。因此,您可以依靠它。

Python 3.6(CPython)

从Python 3.6开始,对于Python的CPython实现,字典默认情况下保持插入顺序。但是,这被认为是实现细节。collections.OrderedDict如果希望在其他Python实现中保证插入顺序,则仍应使用。

Python> = 2.7和<3.6

当您需要dict记住插入项目顺序的时,请使用该类。

Python 3.7+

In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

Python 3.6 (CPython)

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that’s guaranteed across other implementations of Python.

Python >=2.7 and <3.6

Use the class when you need a dict that remembers the order of items inserted.


回答 2

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

使用sorted函数,它对传入的可迭代对象进行排序。

.keys()方法以任意顺序返回键。

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

Use the sorted function, which sorts the iterable passed in.

The .keys() method returns the keys in an arbitrary order.


回答 3

只需在要使用列表时对其进行排序。

l = sorted(d.keys())

Just sort the list when you want to use it.

l = sorted(d.keys())

回答 4

来自http://docs.python.org/tutorial/datastructures.html

“字典对象的keys()方法以任意顺序返回字典中使用的所有键的列表(如果要对其排序,只需对其应用sorted()函数)。”

From http://docs.python.org/tutorial/datastructures.html:

“The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it).”


回答 5

尽管顺序无关紧要,因为字典是哈希图。这取决于将其推入的顺序:

s = 'abbc'
a = 'cbab'

def load_dict(s):
    dict_tmp = {}
    for ch in s:
        if ch in dict_tmp.keys():
            dict_tmp[ch]+=1
        else:
            dict_tmp[ch] = 1
    return dict_tmp

dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))

输出:
对于字符串abbc,键为字符串cbab的dict_keys([‘a’,’b’,’c’])
对于密钥cbab,键为dict_keys([‘c’,’b’,’a’])

Although the order does not matter as the dictionary is hashmap. It depends on the order how it is pushed in:

s = 'abbc'
a = 'cbab'

def load_dict(s):
    dict_tmp = {}
    for ch in s:
        if ch in dict_tmp.keys():
            dict_tmp[ch]+=1
        else:
            dict_tmp[ch] = 1
    return dict_tmp

dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))

output:
for string abbc, the keys are dict_keys([‘a’, ‘b’, ‘c’])
for string cbab, the keys are dict_keys([‘c’, ‘b’, ‘a’])


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。