Dom*_*nus 2 python dictionary ordereddictionary
我正在尝试获取在字典中插入的第一个项目(尚未重新排序)。例如:
_dict = {'a':1, 'b':2, 'c':3}
Run Code Online (Sandbox Code Playgroud)
我想得到元组('a',1)
我怎样才能做到这一点?
在 Python 3.6 之前,字典是无序的,因此“第一个”没有明确定义。如果您想保留插入顺序,则必须使用OrderedDict: https: //docs.python.org/2/library/collections.html#collections.OrderedDict
从 Python 3.6 开始,字典默认保留插入顺序(请参阅如何保持键/值与声明的顺序相同?)
知道了这一点,你只需要做
first_element = next(iter(_dict.items()))
Run Code Online (Sandbox Code Playgroud)
请注意,由于_dict.items()不是迭代器而是可迭代的,因此您需要通过调用 来为其创建迭代器iter。
可以对键和值执行相同的操作:
first_key = next(iter(_dict))
first_value = next(iter(_dict.values()))
Run Code Online (Sandbox Code Playgroud)