473,385 Members | 1,661 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,385 software developers and data experts.

Determining a replacement dictionary from scratch

Dan
Hello,

I'd like to be able to take a formatted string and determine the
replacement dictionary necessary to do string interpolation with it.
For example:
str = 'his name was %(name)s and i saw him %(years)s ago.'
createdict( str ) {'name':'', 'years':''}


Notice how it would automatically fill in default values based on
type. I figure since python does this automatically maybe there is a
clever way to solve the problem. Otherwise I will just have to parse
the string myself. Any clever solutions to this?

Thanks
-dan
Jul 18 '05 #1
4 1338
In article <4b**************************@posting.google.com >, Dan wrote:
I'd like to be able to take a formatted string and determine the
replacement dictionary necessary to do string interpolation with it.
For example:
str = 'his name was %(name)s and i saw him %(years)s ago.'
createdict( str ) {'name':'', 'years':''}


Notice how it would automatically fill in default values based on
type. I figure since python does this automatically maybe there is a
clever way to solve the problem. Otherwise I will just have to parse
the string myself. Any clever solutions to this?


Here's a solution that uses a regular expression. It only handles strings
and doesn't cache the regular expression; I'll leave this up to you. =)

import re
def createdict(fmt):
keys = re.findall('%\(([A-Za-z]+)\)s', fmt)
return dict(zip(keys, [''] * len(keys)))

The regular expression works like this:

%\( - match a percent character and opening parenthesis
([A-Za-z]+) - match a sequence of one or more alpha characters as a GROUP
\)s - match a closing parenthesis and 's' character

For more details on "re", see the documentation:
http://python.org/doc/current/lib/module-re.html

HTH,
Dave

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #2
On 18 Jan 2004 11:16:31 -0800, Dan wrote:
Hello,

I'd like to be able to take a formatted string and determine the
replacement dictionary necessary to do string interpolation with it.
For example:
str = 'his name was %(name)s and i saw him %(years)s ago.'
createdict( str ) {'name':'', 'years':''}


Notice how it would automatically fill in default values based on
type. I figure since python does this automatically maybe there is a
clever way to solve the problem. Otherwise I will just have to parse
the string myself. Any clever solutions to this?

Thanks
-dan


You can use the % operator to look for such constructions. You just
need to define the __getitem__ method of a class to store the
variable names. What about this function:

def createdict(format):
class grab_variables:
def __init__(self):
self.variables = {}
def __getitem__(self, item):
self.variables[item] = ''
g = grab_variables()
format%g
return g.variables

print createdict('his name was %(name)s and i saw him %(years)s ago.')

{'name': '', 'years': ''}
Best regards,
Christophe.
Jul 18 '05 #3
On Sun, Jan 18, 2004 at 07:34:07PM -0000, Dave Benjamin wrote:
Here's a solution that uses a regular expression. It only handles strings
and doesn't cache the regular expression; I'll leave this up to you. =)


Of course, since it uses regular expressions it's also wrong...
createdict("%%(foo)s")

{'foo': ''}

This version might be more correct:

pat = re.compile("%\([^)]*\)s|%%")

def createdict(fmt):
keys = [x[2:-2] for x in pat.findall(fmt) if x != '%%']
return dict(zip(keys, [''] * len(keys)))

Here's another way, one I like better:
class D:
def __init__(self): self.l = []
def __getitem__(self, item): self.l.append(item)

def createdict(fmt):
d = D()
fmt % d
return dict(zip(d.l, [''] * len(d.l)))
... I like it better because it uses the exact same logic to determine
the needed names as it will when the string is actually formatted.

Jeff

Jul 18 '05 #4
Dan
Brilliant, thank you all for your help.

-Dan
Jul 18 '05 #5

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

Similar topics

8
by: Joshua Beall | last post by:
Hi All, I am wondering what the best way to determine an age of something/somone is. For instance, let's say I have two dates: 1985-07-19 2003-11-30 Now, I want to determine the interval...
25
by: Sean Berry | last post by:
Say I have a dictionary like the following {1:'one',2:'two',4:'three',8:'four',16:'five', etc...} and I am given some numbers, say 22, 25, and 9. I want to determine the keys, powers of 2,...
92
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption?...
10
by: CJM | last post by:
I have a bit of code which involves some looping... In each iteration, we retrieve a string value... I want to build a list of DISTINCT (in the SQL sense) string values. Our example strings...
6
by: bear220720 | last post by:
I have a big problem about how to make this C++ program. I was asked to use binary search tree to built a dictionary. This program must have some function, 1. Read a article file and include every...
3
by: chris | last post by:
Hallo, I am in need of a replacement for the Microsoft Visual Studio .NET. The reason is quiet simple. I develop forms which are used on different microsoft windows platform, and one...
8
by: Alexander Walker | last post by:
Hello I am using a Dictionary to store some queues which store instances of a class that I have written I would like to be able to determine whether a particular queue already contains an...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.