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

Search for mapping solution

Hi,
stated in a post befor, I'm a java programmer, fascinated about the elegant
way python solves iterations. Maybe you can show me a solution how to map
the following

I have a List:

Name - Number - Costs

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

Now I want to have it in a dictionary(name,costs) Should look like
{'fred':'0,60' , 'sam':'1'}

What's an elegant way to do it? I can use a lot of loops, but I assume, that
there is a better way of doing so.

Thanks,
Markus
Jul 18 '05 #1
10 1755
"Markus Joschko" <jo****@phreaker.net> wrote in message
news:be************@ID-47851.news.dfncis.de...
Name - Number - Costs

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

Now I want to have it in a dictionary(name,costs) Should look like
{'fred':'0,60' , 'sam':'1'}


I would do it like this:

lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
costs = {}
for name,number,price in lines:
costs[name] = costs.setdefault(name,0)+float(price)
print costs

Achim
Jul 18 '05 #2
Markus Joschko wrote:
Hi,
stated in a post befor, I'm a java programmer, fascinated about the elegant
way python solves iterations. Maybe you can show me a solution how to map
the following

I have a List:

Name - Number - Costs

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

Now I want to have it in a dictionary(name,costs) Should look like
{'fred':'0,60' , 'sam':'1'}

What's an elegant way to do it? I can use a lot of loops, but I assume, that
there is a better way of doing so.


lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
costs = {}
for name, items, price in lines:
costs[name] = costs.setdefault(name, 0.0) +
float(price.replace(',','.'))

print costs
{'fred': 0.59999999999999998, 'sam': 1.0}


regards Max M
Jul 18 '05 #3
Markus Joschko <jo****@phreaker.net> writes:
[...]
I have a List:

nName - Number - Costs

[...]
lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

[...]

Note that tuples were designed for that sort of 'mini-object' use (and
were not intended primarily as immutable lists).

lines = [('fred','333','0,10'), ('sam','444','1'), ('fred','333','0,50')]
though of course it's no disaster if you end up with a list of
3-element lists instead of 3-tuples, if it's convenient to build the
list with zip or whatever.
John
Jul 18 '05 #4
>
Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
d = dict([(x[0], x[2]) for x in lines])
d
{'sam': '1', 'fred': '0,50'}


fred should be 0,60. The 3rd column should be summarized.


OK, I'll write and maintain a 1000-line perl program as penance ...

sometimes-concise-is-elegant-too-ly yrs.


Jul 18 '05 #5
>
lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
costs = {}
for name,number,price in lines:
costs[name] = costs.setdefault(name,0)+float(price)
print costs

thanks it works. But maybe I can complicate the example a little bit
(because in real world it's more complicated):

What if I every list in lines has 20 or more entries and I have only the
index number to access the name, e.g.

lines = [['elem1','elem2','fred','elem3',.......;'elem
17','333','elem18','0.10'],[...],[...]]
what I want to say: I can't be sure that the name is always on the third
position. That's dynamic. I know it before I parse the list, but
I can't say

for elem1,elem2,name,.... cause it can also be

for elem1,name,elem3 ....
Thanks for the answer,
Markus
Jul 18 '05 #6
Sean Ross wrote:
Hi. You've left out the accumulating part of the OP's requirements:


I know :-(

The real temptation I have to resist is deciding to answer someone
question without reading the whole question properly.

I tried to cancel the post as soon as I realised, but it was obviously
too late.

No more posting for me for a while.

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #7
On Sun, 06 Jul 2003 21:17:36 +0200, Markus Joschko <jo****@phreaker.net> wrote:
Hi,
stated in a post befor, I'm a java programmer, fascinated about the elegant
way python solves iterations. Maybe you can show me a solution how to map
the following

I have a List:

Name - Number - Costs

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
Now I want to have it in a dictionary(name,costs) Should look like
{'fred':'0,60' , 'sam':'1'} Should same-name costs just be added, and the number just be ignored?
Assuming so, do you actually want the costs in the final dict to be represented
as localized strings, or should they be floating point numbers -- or, should they
be fixed point in effect?
What's an elegant way to do it? I can use a lot of loops, but I assume, that
there is a better way of doing so.

If the names were all different, it would be a snap
lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]
d = dict([(name,cost) for name,num,cost in lines])
d

{'sam': '1', 'fred': '0,50'}

but, your example seems to have further requirements, so maybe:

====< jocsch.py >==============================================
lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

# might want to use locale-sensitive fixed point for currency, but we'll fake it here ;-)
def str2num(s): return ',' in s and int(s.replace(',','')) or 100*int(s) # units of 0,01
def num2str(n): h,u = divmod(abs(n),100); s='-'[:n<0]; return u and '%s%d,%02d'%(s,h,u) or '%s%d'%(s,h)

d={}
for name,num,cost in lines:
cost = str2num(cost) # units of 0,01
d[name] = d.get(name, 0) + cost # accumulate same-name costs in integral units
for name in d.keys(): d[name] = num2str(d[name]) # mixed literal string syntax again

print lines
print d
================================================== =============
Result:

[14:27] C:\pywk\clp>jocsch.py
[['fred', '333', '0,10'], ['sam', '444', '1'], ['fred', '333', '0,50']]
{'sam': '1', 'fred': '0,60'}

A uniform format (i.e., '1,00' instead of '1') would have simplified conversions a little ;-)

Regards,
Bengt Richter
Jul 18 '05 #8
result = {}
for (name, whatever, costs) in lines:
costs = float(number.replace(',','.'))
dict[name] = dict.get( name, 0.0) + costs

(that's untested, but you should get the idea). Note, however, floating
point is generally a poor choice for accounting applications, so you may
want to look into the libraries for fixed-point calculations.

HTH,
Mike

Markus Joschko wrote:
Hi,
stated in a post befor, I'm a java programmer, fascinated about the elegant
way python solves iterations. Maybe you can show me a solution how to map
the following

I have a List:

Name - Number - Costs

lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']]

Now I want to have it in a dictionary(name,costs) Should look like
{'fred':'0,60' , 'sam':'1'}

What's an elegant way to do it? I can use a lot of loops, but I assume, that
there is a better way of doing so.

Thanks,
Markus

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/


Jul 18 '05 #9
Thanks for all the answers. Nice to have such a community.

For me it's really interesting to see all the possible solutions. I learned
some new things in this discussion

Greetings,
Markus
Jul 18 '05 #10
I dedicate this monument to Alan Kennedy, without whom I would probably
never have tried to compress things so. :-)

Sean Ross <sr***@connectmail.carleton.ca> wrote:
lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
costs = {}
# nearly identical to Achim's solution, but with a list comp.
[costs.__setitem__(name, costs.get(name,0)+float(price))
for name, number, price in lines]
print costs
# outputs: {'sam': 1.0, 'fred': 0.60}


It isn't really one line though, is it? For truly cryptic terseness
you want to swing functional (I shall adopt your interpretation of the
third element although seeing it as a list of integers would have
allowed for additional functional yumminess):
lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
reduce(lambda d,x: d.update({x[0]: d.get(x[0],0.0) + float(x[2])}) or d, [{}] + lines)

{'fred': 0.59999999999999998, 'sam': 1.0}

Mind you, I normally despise the whole one-liner phenomenon, which
makes me almost pleased about the inelegant necessity of that 'or d' -
blame it on either update's lack of a return value or lambda's
emasculation. But as I've been working my way through SICP as this
summer's project, it certainly seems odd. :-/

--
automation: replacing what works with something that almost works,
but which is faster and cheaper. - attributed to Roger Needham
Jul 18 '05 #11

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

Similar topics

4
by: Bosconian | last post by:
I'm looking for a free open source web site search engine. htdig looks like a good one that's well supported and used in the community. I've read over the feature list and documentation, but I'm...
3
by: Benny | last post by:
Hi All, In an application I write, I need to have some mapping service, where I can select two locations, which shall calculate the distance and mainly the time(could be approximate) to travel...
5
by: Deryck | last post by:
Hi, I am working on an e-commerce site. It uses a CMS. One requirement is to have a static off-line version so that the company's sales reps can visit customers and take orders on a laptop...
1
by: Tamas Hegedus | last post by:
Hi! I am looking for an xml-object mapping tool ('XML Data Binding-design time product') where I can define the mapping rules in 'binding files' and the parser is generated automatically. ...
1
by: CV | last post by:
Hello, Could anyone please throw your suggestions on the following scenario? (It would be really helpful if you could provide a solution using ..NET,XSLT,XSD,Web Service other than 'Biztalk...
60
by: Julie | last post by:
What is the *fastest* way in .NET to search large on-disk text files (100+ MB) for a given string. The files are unindexed and unsorted, and for the purposes of my immediate requirements, can't...
2
by: Danny Miller | last post by:
Hi there, I'm facing a problem that is driving me nuts. The scenario is as follows: 1) Create an empty directory structure e.g. C:\Dev1\TestWebApp 2) Map a virtual directory e.g. TestWebApp...
4
by: BentleyInc | last post by:
I'm trying to find a way to add a whildcard application mapping to aspnet_isapi.dll in IIS programmatically.... been looking into IIS administrator reference but didn't find the right function to...
5
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so:...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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...

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.