[Tutor] Re: accessing items in nested structure

Andrei project5 at redrival.net
Mon Mar 22 13:20:04 EST 2004


kevin parks wrote on Mon, 22 Mar 2004 05:13:10 -0500:

> def datas(x):
>      pg01 = [    { (1,0) : [8, 3, 5, 4] },
>              { (7,0) : [4, 3, 2, 2] },
<snip>
>              { (41,1) : [2, 0, 3, 1, 6] }]
>      return pg01[x]

pg01 looks overly complicated to me - it's a very cumbersome way of writing
a dictionary which could look like this:

pg01 = { 
        (1, 0): [8, 3, 5, 4],
        (7, 0): [4, 3, 2, 2],
        <etc.>
       }

If you really need to access the keys by their number, you could use a
sorted dictionary - there's code for it available which is easy to find if
you google for "sorted dictionary python".

Also doing this in a function might not be the best idea. Every time you
call that function, pg01 must be rebuilt, which is not very efficient
(unless Python optimizes it, I don't know). You could just have a global
pg01 and ask for values from it directly in the code using pg01[x].

> want to be able to access each key and its list, that its i want to be 
> able to iterate through this pg01 list and do something to each key and 
> value(list) in the list.

You can iterate over the keys in a dictionary quite easily:

>>> mydict = {0: "a", 1:"b", 2:"c"}
>>> for key in mydict:
...     print key, mydict[key]
...     
0 a
1 b
2 c

Note that although in this case the keys appear to remain sorted, there is
no guarantee that this will always be the case, so if you need them sorted,
either use a sorteddict as mentioned above, or do something like this:

>>> keys = mydict.keys()
>>> keys.sort() # sorts in-place
>>> for key in keys:
...     print key, mydict[key]
...     
0 a
1 b
2 c

> but i am not sure how to get inside the dictionaries inside the pg01 
> and iterate over those and the nested list values.

Well, looping over an item inside some container is not that hard. E.g.:

>>> nestedlist = [[0, 1], [2, 3], [4, 5]]
>>> for element in nestedlist:
...     print element, # element is now one item in nestedlist
...     for subelement in element:
...         print subelement,
...     print ''
...     
[0, 1] 0 1 
[2, 3] 2 3 
[4, 5] 4 5 

You can combine this with the keys thing I showed above for dictionaries to
loop over keys in a dictionary inside a list or whatever else you might
fancy.

> Also since my dictionary keys are not consecutive numbers how can i be 
> sure to hit them all?

Use - as demonstrated above - either 'for key in somedictionary' or 'for
key in somedictionary.keys()'. That gives you each key in that dictionary
exactly once.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list