The order of keys in dictionaries

前端 未结 6 985
渐次进展
渐次进展 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: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'])

提交回复
热议问题