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:
...
Cuthbert Grub Dibble
And if you do want an associated number, there's enumerate:
...
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