Dict lookup shortcut?

Bengt Richter bokr at oz.net
Wed Oct 13 02:54:32 CEST 2004


On Tue, 12 Oct 2004 12:39:23 +0100, "M. Clift" <noone at here.com> wrote:

>Hi All,
>
>Can someone tell me is there a shorthand version to do this?
>
First question is why you want to do "this" -- and what "this" really is ;-)

>l1 = ['n1', 'n3', 'n1'...'n23'...etc...]
>
Where does that list of names come from?

>Names = {'n1':'Cuthbert','n2' :'Grub','n3' :'Dibble' etc...}
>
>for name in l1:
>    print Names[name],
>
>Rather than listing all the name+numbers keys in the dictionary can these
>keys be shortened somehow into one key and a range?
>


 >>> Names = dict([('n%s'%(i+1), name) for i,name in enumerate('Cuthbert Grub Dibble'.split())])
 >>> Names
 {'n1': 'Cuthbert', 'n2': 'Grub', 'n3': 'Dibble'}
 >>> for key in Names: print Names[key],
 ...
 Cuthbert Grub Dibble

I doubt that's what you really wanted to do, but who knows ;-)

BTW, in general, you can't depend on the order of keys gotten from a dictionary.

So if the dictionary pre-existed with those systematic sortable keys, you could
get them without knowing how many keys there were, and sort them instead of making
a manual list. E.g.,

 >>> keys = Names.keys()
 >>> keys.sort()
 >>> for key in keys: print Names[key],
 ...
 Cuthbert Grub Dibble

OTOH, if you are storing names in numerical order and want to retrieve them by
a key that represents their numerical position in the order, why not just use
a list and index it by numbers? E.g.

 >>> NameList = 'Cuthbert Grub Dibble'.split()
 >>> NameList
 ['Cuthbert', 'Grub', 'Dibble']
 >>> NameList[0]
 'Cuthbert'
 >>> NameList[2]
 'Dibble'

Plus, you don't have to bother with indices or sortable names at all
if you want to process them in order:

 >>> for name in NameList: print name,
 ...
 Cuthbert Grub Dibble

And if you do want an associated number, there's enumerate:

 >>> for i,name in enumerate(NameList): print 'Name #%2s: "%s"'%(i+1,name)
 ...
 Name # 1: "Cuthbert"
 Name # 2: "Grub"
 Name # 3: "Dibble"

Notice that I added 1 to i in order to print starting with # 1, since enumerate starts with 0 ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list