The order of keys in dictionaries

前端 未结 6 899
渐次进展
渐次进展 2020-11-22 14:32

Code:

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

print l

This prints [\'a\', \'c\', \'b\']. I\'m unsure of how the metho

相关标签:
6条回答
  • 2020-11-22 14:44

    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 collections.OrderedDict class when you need a dict that remembers the order of items inserted.

    0 讨论(0)
  • 2020-11-22 14:48

    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.

    0 讨论(0)
  • 2020-11-22 14:50

    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'])

    0 讨论(0)
  • 2020-11-22 14:55

    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)."

    0 讨论(0)
  • 2020-11-22 14:58
    >>> 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.

    0 讨论(0)
  • 2020-11-22 15:09

    Just sort the list when you want to use it.

    l = sorted(d.keys())
    
    0 讨论(0)
提交回复
热议问题