Maxime
Maxime

Reputation: 634

Colon : operator in a list

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,

Upvotes: 0

Views: 1155

Answers (1)

janos
janos

Reputation: 124724

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']

Upvotes: 3

Related Questions