bob*_*h76 4 python dictionary cpython python-3.6
既然字典是在python 3.6中排序的,那么必须有一种方法可以只用两行来获取字典的第一个和第二个值.现在,我必须用7行来完成这个:
for key, value in class_sent.items():
i += 1
if i == 1:
first_sent = value
elif i == 2:
second_sent = value
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
first_sent = next(iter(class_sent))
second_sent = next(iter(class_sent))
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,second_sent等于first_sent.如果有人知道如何在尽可能少的行中获取字典中的第一个和第二个值,我会非常感激.
现在Python只保证**kwargs保留顺序和类属性.
考虑到你正在使用的Python的实现保证了你可以做的这种行为.
>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)
Run Code Online (Sandbox Code Playgroud)
iter().>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)
Run Code Online (Sandbox Code Playgroud)
>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
Run Code Online (Sandbox Code Playgroud)