Search code examples
pythondictionarypython-3.6cpython

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.


Solution

  • 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)