Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first and second values in dictionary in CPython 3.6

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.

like image 517
bobsmith76 Avatar asked Jul 04 '17 22:07

bobsmith76


1 Answers

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.

  1. Using itertools.islice.

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

>>> it = iter(dct.values())    
>>> first, second = next(it), next(it)    
>>> first, second
(1, 2)
  1. Using extended iterable unpacking(will result in unnecessary unpacking of other values as well):

>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
like image 89
Ashwini Chaudhary Avatar answered Oct 24 '22 10:10

Ashwini Chaudhary