如何获取 python 字典中的顺序数据?
How can I get data with order in python dictionary?
我想在订单中取回钥匙。但是,它不适用于字典和 Collections.OrderedDict.
from collections import OrderedDict
data = OrderedDict({
"Name1": "value1",
"Name2": "value2"
})
for key in data.keys():
print(key)
此代码显示Name3 Name4 ...
。它没有任何顺序。我的数据在键中没有字母顺序,我必须按顺序获取键。
我发现词典没有按顺序设计。那么,键值对可以使用哪些结构呢?或者有什么方法可以按自定义顺序使用字典? (输入顺序..?)
您需要从这个
更改您的有序字典的结构
data = OrderedDict({
"Name1": "value1",
"Name2": "value2",
...
})
至此
data = OrderedDict([('Name1', 'value1'), ('Name2', 'Value2')])
tl;dr:使用 Python 3.7 或更高版本。
dict
s in Python 3.7 and above are always ordered。这适用于各种迭代:
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
这个also applies to the popitem()
method:
Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.
https://docs.python.org/3/library/stdtypes.html#dict.popitem
我想在订单中取回钥匙。但是,它不适用于字典和 Collections.OrderedDict.
from collections import OrderedDict
data = OrderedDict({
"Name1": "value1",
"Name2": "value2"
})
for key in data.keys():
print(key)
此代码显示Name3 Name4 ...
。它没有任何顺序。我的数据在键中没有字母顺序,我必须按顺序获取键。
我发现词典没有按顺序设计。那么,键值对可以使用哪些结构呢?或者有什么方法可以按自定义顺序使用字典? (输入顺序..?)
您需要从这个
更改您的有序字典的结构data = OrderedDict({
"Name1": "value1",
"Name2": "value2",
...
})
至此
data = OrderedDict([('Name1', 'value1'), ('Name2', 'Value2')])
tl;dr:使用 Python 3.7 或更高版本。
dict
s in Python 3.7 and above are always ordered。这适用于各种迭代:
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
这个also applies to the popitem()
method:
Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.
https://docs.python.org/3/library/stdtypes.html#dict.popitem