Get first and second values ​​in a dictionary in CPython 3.6

Now that the dictionaries are ordered in python 3.6 it should be that there is a way to get the first and second values ​​of the dictionary in just 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've also tried:

first_sent = next(iter(class_sent))
    second_sent = next(iter(class_sent))

      

But in this case, second_sent is equal to first_sent. If anyone knows how to get the first and second values ​​in a dictionary in as few lines as possible, I would seriously appreciate it.

+3


source to share


2 answers


Right now Python only guarantees that the order **kwargs

and attributes of the class are preserved .

Considering the Python implementation you are using guarantees the kind of behavior you could do.

>>> from itertools import islice    
>>> dct = {'a': 1, 'b': 2, 'c': 3}    
>>> first, second = islice(dct.values(), 2)    
>>> first, second
(1, 2)

      

  1. Use iter()

    .


>>> it = iter(dct.values())    
>>> first, second = next(it), next(it)    
>>> first, second
(1, 2)

      

  1. Using advanced iterative unboxing (will result in unnecessary unboxing of other values):

>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)

      

+6


source


This might work:



first_sent, second_sent = list(class_sent.values())[:2]

      

0


source







All Articles