473,698 Members | 2,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String formatting with dictionaries

Consider the following simple dictionary
e={1:'one', 2: 'two'}
e[1]
'one'


However, If I attempt to print e[1] using a formatted string
print " %(1)s" %e,

I get a KeyError: '1'

Clearly Python is converting the number 1 to the string '1' before
looking it up in the dictionary. Furthermore, this seems to happen
only when creating formatted strings: the dictionary can be directly
accessed as shown above. How can I modify my formatted string
statement to correctly access the dictionary.

I am aware that I can make it work by changing e to
e={'1':'one', '2': 'two'}
but I do want to find out

a) what is needed make it work in its current form, and
b) why it does not work in the seemingly obvious way I have written it
above

Sincerely
Thomas Philips
Jul 18 '05 #1
5 3020
tk****@hotmail. com (Thomas Philips) wrote in
news:b4******** *************** ***@posting.goo gle.com:
Clearly Python is converting the number 1 to the string '1' before
looking it up in the dictionary. Furthermore, this seems to happen
only when creating formatted strings: the dictionary can be directly
accessed as shown above. How can I modify my formatted string
statement to correctly access the dictionary.


The mapping key is a sequence of characters, i.e. it already is a string.
Python is not converting it to a string, it is simply not converting it
into a number.

To make it work, you could subclass dict so that strings get converted to
integers automatically on lookup, or just convert the keys to strings:

print " %(1)s" % dict([(str(k),e[k]) for k in e])

Jul 18 '05 #2
tk****@hotmail. com (Thomas Philips) writes:
I am aware that I can make it work by changing e to
e={'1':'one', '2': 'two'}
but I do want to find out

a) what is needed make it work in its current form, and
What you just did above - use strings as keys in your dictionary.
b) why it does not work in the seemingly obvious way I have written it
above


Perhaps probably because your intuition isn't firmly grounded in Dutch
sensibilities? Or I could just say "because that's not how the string
formatting operator works" but that doesn't help much does it :-)

If we come at it from your "obvious" comment, one could ask why you
think it treating it as a number is obvious? When you write:

"blah blah blah %(name)s blah blah" % some_dict

The formatting operator upon finding "%(name)s", looks up "name" in
the dictionary and then applies the "s" (string) format to it. If you
think about it the formatting operator just has access to your format
string as, in fact, a string. And in the specific case of dictionary
keys, the element in between the () is a label to be used (a sequence
of characters as per 2.3.6.2 in the library reference, and both there
and 7.1 in the tutorial show examples using string keys).

Now, there's no additional markup in the format string to indicate
that the dictionary key is anything other than a sequence of
characters, and since in general Python tries to avoid ever guessing
at what you mean, it just uses those characters directly.

In other words, you may see the "1" in the format string as a number,
but you've entered it into your program as part of a string, and
that's how Python (and the string formatting operator) see it. Maybe
not what you desired, but it's how the formatting operator works in
this case.

-- David

Jul 18 '05 #3
In article <b4************ **************@ posting.google. com>,
tk****@hotmail. com (Thomas Philips) wrote:
Consider the following simple dictionary
e={1:'one', 2: 'two'}
e[1]
'one'
However, If I attempt to print e[1] using a formatted string
print " %(1)s" %e,

I get a KeyError: '1'

Clearly Python is converting the number 1 to the string '1' before
looking it up in the dictionary.
Not clear at all. Any immutable value can be a
dictionary key.

The mapping key is a sequence of characters in a format
string.. a slice of a string, you might say, and it will
only match a key that is a string.

Furthermore, this seems to happen
only when creating formatted strings: the dictionary can be directly
accessed as shown above. How can I modify my formatted string
statement to correctly access the dictionary.

I am aware that I can make it work by changing e to
e={'1':'one' , '2': 'two'}
but I do want to find out

a) what is needed make it work in its current form, and
b) why it does not work in the seemingly obvious way I have written it
above


It wouldn't be enough the make %(1)s retrive 'one' in the
dictionary e; you'd actually be interpreting Python
expressions inside the format string, and people would
require %(7-5)s to come out as two, just like e[7-5] did.
f={'7-5':'three'}
print "%(7-5)s" % f

three
Regards. Mel.
Jul 18 '05 #4
Thomas> I am aware that I can make it work by changing e to
Thomas> e={'1':'one', '2': 'two'}
Thomas> but I do want to find out

Thomas> a) what is needed make it work in its current form, and

How about subclassing dict so that __getitem__ tries calling int() on the
key it's presented if it fails to find the key?

class mydict(dict):
### untested! ###
def __getitem__(sel f, key):
try:
return dict.__getitem_ _(self, key)
except KeyError:
try:
key = int(key)
except ValueError:
raise
else:
return dict.__getitem_ _(self, key)

Thomas> b) why it does not work in the seemingly obvious way I have
Thomas> written it above

Because strings are not ints.

Skip

Jul 18 '05 #5
David Bolen wrote:
b) why it does not work in the seemingly obvious way I have written it
above

Perhaps probably because your intuition isn't firmly grounded in Dutch
sensibilities? Or I could just say "because that's not how the string
formatting operator works" but that doesn't help much does it :-)


Funny, but when I read Thomas' original post, I thought
what he expected was blindingly obvious and
intuitive... but once it was pointed out that the keys
were being taken from a string, it became blindingly
obvious and intuitive that they had to be strings
themselves!

It's a funny old world, inn't?
--
Steven
Jul 18 '05 #6

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

Similar topics

8
1769
by: Michele Simionato | last post by:
I was playing with string.Template in Python 2.4 and I came out with the following recipe: import sys from string import Template def merge(*dictionaries): """Merge from right (i.e. the rightmost dictionary has the precedence).""" merg = {} for d in dictionaries:
1
1207
by: anuraguniyal | last post by:
Hi, ''%() doesn't raise exception but ''%('') does Can anyone explain me why?? rgds Anurag
10
4833
by: Oliver S. | last post by:
I've developed a string-class that holds the string in an array which is a member-variable of the class and that has maximum-size which is con- figurable through a template-parameter. If any operation would grow the string beyond its maximum size, an exeception would be thrown. This kind of string obviously has superior performance over a std::string because there's never any additional memory-allocation. But before I'm going to re-invent...
20
11313
by: hagai26 | last post by:
I am looking for the best and efficient way to replace the first word in a str, like this: "aa to become" -> "/aa/ to become" I know I can use spilt and than join them but I can also use regular expressions and I sure there is a lot ways, but I need realy efficient one
7
398
by: ilona | last post by:
Hi all, I store phone numbers in the database as 123447775665554(input mask is used for input, and some numbers have extensions), and I also know from db if the number is Canadian, US, or some other country. When I retrieve the phone numbers, I need to display them as (###) ###-#### x 99999 if it is a Canadian number or (###) ###-#### Ext. 99999 if it is US phone number. Potentially I'd have other countries added as well which might have...
7
3109
by: L. Scott M. | last post by:
Have a quick simple question: dim x as string x = "1234567890" ------------------------------------------------------- VB 6 dim y as string
5
5575
by: linnorm | last post by:
I've got a bit of code which has a dictionary nested within another dictionary. I'm trying to print out specific values from the inner dict in a formatted string and I'm running into a roadblock. I can't figure out how to get a value from the inner dict into the string. To make this even more complicated this is being compiled into a large string including other parts of the outer dict. mydict = {'inner_dict':{'Value1':1, 'Value2':2},...
3
2507
by: Rich Shepard | last post by:
I need to learn how to process a byte stream from a form reader where each pair of bytes has meaning according to lookup dictionaries, then use the values to build an array of rows inserted into a sqlite3 database table. Here's the context: The OMR card reader sends a stream of 69 bytes over the serial line; the last byte is a carriage return ('\r') indicating the end of record. Three pairs (in specific positions at the beginning of the...
14
4333
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my unformatted data values (as decimals) just fine, so I know there's not a problem with the data retrieval, just the formatting. I have read that this would work: lblPrice.Text = prodRow.ToString("C");
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8876
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
7741
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...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5867
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();...
1
3052
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
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.