473,657 Members | 2,411 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dict lookup shortcut?

Hi All,

Can someone tell me is there a shorthand version to do this?

l1 = ['n1', 'n3', 'n1'...'n23'... etc...]

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?

Thanks,

M
Jul 18 '05 #1
5 1289
M. Clift wrote:
Hi All,

Can someone tell me is there a shorthand version to do this?

l1 = ['n1', 'n3', 'n1'...'n23'... etc...]

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?

Thanks,

M


I'm not sure what you're trying to do, but you should probably be doing
this instead:

names = {'n1':'Cuthbert ', 'n2':'Grub', 'n3':'Dibble'}

for key in names.keys():
print names[key],

No need for the initial list. Alternatively, you could just have all the
names in a list to start with and iterate over that:

names = ['Cuthbert', 'Grub', 'Dibble']

for name in names:
print name,

Dan

NB: all code untested
Jul 18 '05 #2
M. Clift wrote:
Hi All,

Can someone tell me is there a shorthand version to do
this?

l1 = ['n1', 'n3', 'n1'...'n23'... etc...]

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?


I'm not sure what you want to do:

l1= [...]
Names = {'n': l1}
print Names[n][12]

Or maybe you meant:

for i in range(1,24):
Names['n'+`i`]=blah

If that didn't answer your question, please rephrase it. And BTW, variables (like Names) are spelled lowercase (i.e., names) by
convention; it's only class names that usually get capitalized (though it's no fixed rule).
Jul 18 '05 #3
"M. Clift" <no***@here.com > wrote in message news:<ck******* **@newsg2.svr.p ol.co.uk>...
Hi All,

Can someone tell me is there a shorthand version to do this?

l1 = ['n1', 'n3', 'n1'...'n23'... etc...]

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?

You could just use the integers as keys.

*Or* you could do :
alist = Names.items()
alist.sort()
alist[n][1] is the nth name
(alist[n] = (nth key, nth name) )

HTH

Fuzzy
Thanks,

M

Jul 18 '05 #4
On Tue, 12 Oct 2004 12:39:23 +0100, "M. Clift" <no***@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('Cuth bert 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(NameL ist): 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
Jul 18 '05 #5
Hi,

Thankyou all for your replies, they are of great help.

Malcolm
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2007
by: Christopher J. Bottaro | last post by:
If I have the following class: class MyClass: def __init__(self): m_dict = {} m_dict = 1 m_dict = 2 m_dict = 3 Is there anyway to generate automatic accessors to the elements of the dict?
8
2143
by: bearophileHUGS | last post by:
I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less memory, not storing values? Maybe this requires too much code rewriting). I presume such sets are like this because they are kind of dicts. If this is true, then converting a dict to a set (that means converting just the keys; this is often useful for...
8
1418
by: OPQ | last post by:
Hi all, I'd happy to have you share some thougts about ultimate optimisations on those 2 topics: (1)- adding one caractere at the end of a string (may be long) (2)- in a dict mapping a key to a list of int, remove every entrie where the list of int have of length < 2
11
1915
by: Ville Vainio | last post by:
I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). >> d = CiDict() >> d 12
1
485
by: barnesc | last post by:
Hi again, Since my linear algebra library appears not to serve any practical need (I found cgkit, and that works better for me), I've gotten bored and went back to one of my other projects: reimplementing the Python builtin classes list(), set(), dict(), and frozenset() with balanced trees (specifically, counted B-trees stored in memory). In short, this allows list lookup, insertion, deletion in O(log(N)) time. It allows the set and...
1
1301
by: jslowery | last post by:
Hmm, I know this is something fundamental about how Python implements predicate dispatch, but for some reason I believed that this would work: class delegate_dict(dict): def __init__(self, orig, deleg): dict.__init__(self, orig) self.deleg = deleg def __getitem__(self, name):
4
11601
by: Emin | last post by:
Dear Experts, How much slower is dict indexing vs. list indexing (or indexing into a numpy array)? I realize that looking up a value in a dict should be constant time, but does anyone have a sense of what the overhead will be in doing a dict lookup vs. indexing into a list? Some ad hoc tests I've done indicate that the overhead is less than 15% (i.e., dict lookups seem to take no more than 15% longer than indexing into a list and there...
22
2083
by: mrkafk | last post by:
Hello everyone, I have written this small utility function for transforming legacy file to Python dict: def lookupdmo(domain): lines = open('/etc/virtual/domainowners','r').readlines() lines = for x in lines]
20
2414
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001: ,
0
8397
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8827
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7333
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4158
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2731
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1957
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1620
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.