473,761 Members | 9,379 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 3021
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
1773
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
1210
by: anuraguniyal | last post by:
Hi, ''%() doesn't raise exception but ''%('') does Can anyone explain me why?? rgds Anurag
10
4844
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
11326
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
3117
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
5578
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
2515
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
4360
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
9522
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
10111
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...
1
9902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
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
8770
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
7327
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
5215
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...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2738
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.