[Tutor] List within Dictionary

Kent Johnson kent37 at tds.net
Wed Jun 20 13:52:56 CEST 2007


pearl jb wrote:
> I wanted to know "How to access the list elements which is in Dictionary" 
> 
> dict = {'John':['ph=919873673','res=91928827737'] , 'William' : 
> ['ph=91983763','res=91837474848'] }
> 
> 
> I want the output to be
> 
> 1. John res=91928827737
> 2. William ph=91983763

You can use dict.items() to iterate over key, value pairs, then access 
the elements of the value list using regular list indexing. I'm not sure 
how you want to select res for John and ph for William so here is an 
example that prints res for both:

In [11]: d = {'John':['ph=919873673','res=91928827737'] , 'William' : 
['ph=91983763','res=91837474848'] }
In [12]: for name, phones in d.items():
    ....:     print name, phones[1]

William res=91837474848
John res=91928827737


Note that the ordering of keys is essentially random. If you want the 
list in order by name, you can sort the items:

In [13]: for name, phones in sorted(d.items()): 

     print name, phones[1]

John res=91928827737
William res=91837474848


Using enumerate() and some string formatting will give you a sequence 
number:

In [17]: for i, (name, phones) in enumerate(sorted(d.items())):
     print '%s. %s %s' % (i+1, name, phones[1])

1. John res=91928827737
2. William res=91837474848

Docs:
dict.items(): http://docs.python.org/lib/typesmapping.html#l2h-294
sorted(): http://docs.python.org/lib/built-in-funcs.html#l2h-68
enumerate(): http://docs.python.org/lib/built-in-funcs.html#l2h-24
string formatting: http://docs.python.org/lib/typesseq-strings.html

Two more notes:
- Don't use dict as the name for a dict (or list to name a list, or str 
to name a string) as it shadows the name of the built-in type.
- Please don't send HTML mail to the list - use plain text

Kent


More information about the Tutor mailing list