Indexing Help

This is the place for queries that don't fit in any of the other categories.

Indexing Help

Postby sedavidw » Tue Feb 26, 2013 7:56 pm

I'm new to python and am trying to do an indexing method similar to MATLAB and am wondering what I'm doing wrong or if it can be done at all.

I have a structure d where I can access ID's at certain indexes like so

Code: Select all
x = d['content'][6]['id']

The above works fine

I want however an easy way to get a list of all the ID's. I've tried the following:
Code: Select all
x = d['content'][:]['id']

Code: Select all
x = d['content'][0:l-1]['id'] #l is the number of indexes


Can anything like this be done in python? Thanks in advance for your help
sedavidw
 
Posts: 4
Joined: Tue Feb 26, 2013 7:50 pm

Re: Indexing Help

Postby micseydel » Tue Feb 26, 2013 8:08 pm

How about
Code: Select all
ids = [content['id'] for content in d['content']]

By the way, when you index a list you get an element of the list and when you slice a list you get a new list with those elements. So it should make sense that you can't just try to slice the whole list and then index into the list like you would an element in the list. Further, the expression d['content'][:] is equivalent to d['content'] in that they are equal, same type, same interface, etc. and only differ in that one is a copy of the other (which doesn't matter here).
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Indexing Help

Postby sedavidw » Tue Feb 26, 2013 9:11 pm

This solution works great thanks!

micseydel wrote:How about
Code: Select all
ids = [content['id'] for content in d['content']]

By the way, when you index a list you get an element of the list and when you slice a list you get a new list with those elements. So it should make sense that you can't just try to slice the whole list and then index into the list like you would an element in the list. Further, the expression d['content'][:] is equivalent to d['content'] in that they are equal, same type, same interface, etc. and only differ in that one is a copy of the other (which doesn't matter here).
sedavidw
 
Posts: 4
Joined: Tue Feb 26, 2013 7:50 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], W3C [Linkcheck] and 3 guests