字典和OrderedDict之间的区别 [英] Difference between dictionary and OrderedDict

查看:100
本文介绍了字典和OrderedDict之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取排序字典.但是mydictorddict之间的项目顺序似乎没有变化.

I am trying to get a sorted dictionary. But the order of the items between mydict and orddict doesn't seem to change.

from collections import OrderedDict

mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

orddict = OrderedDict(mydict)

print(mydict, orddict)

# print items in mydict:
print('mydict')
for k, v in mydict.items():
    print(k, v)

print('ordereddict')
# print items in ordered dictionary
for k, v in orddict.items():
    print(k, v)


# print the dictionary keys
# for key in mydict.keys():
#     print(key)


#  print the dictionary values
# for value in mydict.values():
#     print(value)

推荐答案

OrderedDict保留插入的订单元素:

An OrderedDict preserves the order elements were inserted:

>>> od = OrderedDict()
>>> od['c'] = 1
>>> od['b'] = 2
>>> od['a'] = 3
>>> od.items()
[('c', 1), ('b', 2), ('a', 3)]
>>> d = {}
>>> d['c'] = 1
>>> d['b'] = 2
>>> d['a'] = 3
>>> d.items()
[('a', 3), ('c', 1), ('b', 2)]

因此OrderedDict不会为您排序元素,而是保留您赋予它的顺序.

So an OrderedDict does not order the elements for you, it preserves the order you give it.

如果您想对字典进行排序",则可能需要

If you want to "sort" a dictionary, you probably want

>>> sorted(d.items())
[('a', 1), ('b', 2), ('c', 3)]

这篇关于字典和OrderedDict之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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