Now that dictionaries are ordered in python 3.6, it must be the case that there is a way to get the first and second values of a dictionary in only two lines. Right now, I have to use 7 lines to accomplish this:
for key, value in class_sent.items():
i += 1
if i == 1:
first_sent = value
elif i == 2:
second_sent = value
I also tried:
first_sent = next(iter(class_sent))
second_sent = next(iter(class_sent))
But in that case the second_sent is equal to the first_sent. If anyone knows how to obtain the first and second values in a dictionary in as few lines as possible I would seriously appreciate it.
Right now Python only guarantees that the order of **kwargs
and class attributes are preserved.
Considering that the implementation of Python you're using guarantees this behaviour you could do.
itertools.islice
.>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)
iter()
.>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)
>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With