473,386 Members | 1,973 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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 2999
tk****@hotmail.com (Thomas Philips) wrote in
news:b4**************************@posting.google.c om:
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__(self, 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
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...
1
by: anuraguniyal | last post by:
Hi, ''%() doesn't raise exception but ''%('') does Can anyone explain me why?? rgds Anurag
10
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...
20
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...
7
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...
7
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
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. ...
3
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...
14
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...

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.