dictionaries with nested lists

A

Alex Martelli

ruari said:
can i write


  • to mean the 3rd item in the list that is the corresponding value for 'key'
    ?


  • No, but you can write dictionary[key][2] for that purpose:

    -- that
    • notation is unneeded and unsupported,
      -- indices start from 0 so the 3rd one is indexed as [2]


      Alex
 
A

Alex Martelli

ruari said:
what if i mean
bands={'beatles':['john','paul','george','ringo'],['guitar','bass','guitar',
'drums']}

Invalid syntax.
then i need to put bands['beatles'][1][3]='percussion'

If you mean that bands is a dictionaries of tuples of lists, yes, but you
need parentheses around the tuples (and I would suggest some formatting
for greater readability), e.g.:

bands = {'beatles': ( ['john', 'paul', 'george', 'ringo'],
['guitar', 'bass', 'guitar', 'drums'] )
}


Alex
 
R

Raymond Hettinger

[ruari mactaggart]
what if i mean
bands={'beatles':['john','paul','george','ringo'],['guitar','bass','guitar',
'drums']}

then i need to put bands['beatles'][1][3]='percussion'

i presume... ?

No need to presume.
Just fire up the interpreter and see.

Compared to comp.lang.python responders,
the results are instant, always accurate, and
immediately available for exploring alternatives.


Raymond Hettinger
 
R

ruari mactaggart

what if i mean
bands={'beatles':['john','paul','george','ringo'],['guitar','bass','guitar',
'drums']}

then i need to put bands['beatles'][1][3]='percussion'

i presume... ?

Joe Francia said:
ruari said:
can i write
dictionary[key]
  • [3]


  • to mean the 3rd item in the list that is the corresponding value for
  • 'key' ?

    You don't need the
    • part. Assuming you mean something like:

      bands = {'beatles': ['john','paul','george','ringo']}

      ...then bands['beatles'][3] == 'ringo'

      Peace,
      Joe
 
F

Francis Avila

ruari mactaggart said:
what if i mean
bands={'beatles':['john','paul','george','ringo'],['guitar','bass','guitar',
'drums']}

then i need to put bands['beatles'][1][3]='percussion'

i presume... ?

If things are getting this complicated, you're probably better off a)
wrapping an interface to this dict using an object, or b) just using object
attributes and using those objects as dictionary items.

Oh, and you need to group those two lists into a single list or tuple....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top