Colon : operator in a list

Question:

I am used to use Matlab and its powerful colon operator.
It seems that there is the equivalent in Python, but not completely when it contains dict.
Here is my example :

data = [
    {'key1' : 'value1', 'key2' : 'value2'},
    {'key1' : 'value3', 'key2' : 'value4'},
    {'key1' : 'value1', 'key2' : 'value5'}
]

data[0:2] works and returns [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}] (however i would have instinctively used 0:1 to have this same result)

but

data[0:2]['key2'] doesn’t and returns list indices must be integers, not str

Should I conclude that : can be used only on list not containing dict, or I am typing it wrong?

Thanks,

Asked By: Maxime

||

Answers:

Should I conclude that : can be used only on list not containing dict, or I am typing it wrong?

That’s not a correct conclusion. : can be used with any list.

The problem is that data[0:2] is a list.
If you want to get a list of the 'key2' values of the elements in data[0:2] then you need to write that as a list comprehension:

>>> [v['key2'] for v in data[0:2]]
... ['value2', 'value4']

If you prefer to use an operator instead of a list comprehension, you can use the following:

>>> from operator import itemgetter
>>> map(itemgetter('key2'), data[0:2])
... ['value2', 'value4']
Answered By: janos
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.