user3053452
user3053452

Reputation: 675

Get n-th element from all dictionary values - Python

Is there any out of the box syntax/func that would return n-th value of all dictionary keys. For example n=2 for the following dic

dic = {'a': [1, 2, 3, 4],
       'b': [5, 6, 7, 8],
       'c': [9, 10, 11, 12]}

would return:

newdic = {'a': 3,
          'b': 7,
          'c': 11}

For now I defined the following function which works fine, but I find it kind of ugly.

def nth_value(n, **kwargs):
    dic = {}
    for key, value in kwargs.items():
        dic[key] = value[n]
    return dic

P.S. I know for sure that all lists are of same length.

Upvotes: 2

Views: 1967

Answers (2)

Kruupös
Kruupös

Reputation: 5474

Improvement to avoid IndexError: list index out of range:

>>> dic = {'a': [1, 2, 3, 4],
           'b': [5, 6, 7, 8],
           'c': [9, 10, 11, 12]}

>>> n = 3
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': 8, 'c': 12}

>>> del dic['b'][-1]
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': None, 'c': 12}

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11144

Try this:

>>> n = 2 
>>> {k:v[n] for k,v in dic.items()}
{'c': 11, 'b': 7, 'a': 3}

Upvotes: 6

Related Questions