473,915 Members | 5,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Summing into a Dictionary

2 New Member
Hi,

Programming in perl and running through lines in a text file, when wanting to sum the area by a key (repeating) variable I am used to using the syntax:
$Hash{$var1}[0] += $area
And then using a foreach loop to get out the total area for each variable.
What is the translation into python for this?

Thanks
Jul 18 '07 #1
5 1605
ghostdog74
511 Recognized Expert Contributor
Hi,

Programming in perl and running through lines in a text file, when wanting to sum the area by a key (repeating) variable I am used to using the syntax:
$Hash{$var1}[0] += $area
And then using a foreach loop to get out the total area for each variable.
What is the translation into python for this?

Thanks
Expand|Select|Wrap|Line Numbers
  1. myDict[var1][0]+=area
  2.  
Jul 18 '07 #2
tbline
2 New Member
Expand|Select|Wrap|Line Numbers
  1. myDict[var1][0]+=area
  2.  
That is what I have been trying, however when I do, I get the following error:

myDict[au][0]+=area
KeyError: 5

This is the jist of my code so far:
Expand|Select|Wrap|Line Numbers
  1. myDict={}
  2.  
  3. for line in f:
  4.         vals = line.strip('\n').split('|')
  5.         stand_num = vals[0]
  6.         access    = vals[3]
  7.         au        = int(vals[7])
  8.         area      = float(vals[9])
  9.  
  10.  
  11.         if au != 99:
  12.                  myDict[au][0]+=area

What does KeyError:5 mean and how I can fix it?

Thanks
Jul 19 '07 #3
bvdet
2,851 Recognized Expert Moderator Specialist
That is what I have been trying, however when I do, I get the following error:

myDict[au][0]+=area
KeyError: 5

This is the jist of my code so far:

myDict={}

for line in f:
vals = line.strip('\n' ).split('|')
stand_num = vals[0]
access = vals[3]
au = int(vals[7])
area = float(vals[9])


if au != 99:
myDict[au][0]+=area


What does KeyError:5 mean and how I can fix it?

Thanks
myDict does not contain the key 5, therefore the key error. Try this instead:
Expand|Select|Wrap|Line Numbers
  1. if myDict.has_key(au):
  2.     myDict[au][0] += area
  3. else:
  4.     myDict[au] = whatever
Jul 19 '07 #4
bartonc
6,596 Recognized Expert Expert
That is what I have been trying, however when I do, I get the following error:

myDict[au][0]+=area
KeyError: 5

This is the jist of my code so far:
Expand|Select|Wrap|Line Numbers
  1. myDict={}
  2.  
  3. for line in f:
  4.         vals = line.strip('\n').split('|')
  5.         stand_num = vals[0]
  6.         access    = vals[3]
  7.         au        = int(vals[7])
  8.         area      = float(vals[9])
  9.  
  10.  
  11.         if au != 99:
  12.                  myDict[au][0]+=area

What does KeyError:5 mean and how I can fix it?

Thanks
See how much nicer it looks when CODE tags are used. To learn how to use them, look to the right. Third point down under REPLY GUIDELINES. Thanks for taking the time,
Moderator
Jul 19 '07 #5
elbin
27 New Member
myDict does not contain the key 5, therefore the key error. Try this instead:
Expand|Select|Wrap|Line Numbers
  1. if myDict.has_key(au):
  2.     myDict[au][0] += area
  3. else:
  4.     myDict[au] = whatever
And the 'whatever' should be a list with the area if you're going to use the [0] index:
Expand|Select|Wrap|Line Numbers
  1. if myDict.has_key(au):
  2.     myDict[au][0] += area
  3. else:
  4.     myDict[au] = [area]
Or simpler (no index if there will be only one value):
Expand|Select|Wrap|Line Numbers
  1. if myDict.has_key(au):
  2.     myDict[au] += area
  3. else:
  4.     myDict[au] = area
OR simpler still ;) :
Expand|Select|Wrap|Line Numbers
  1. myDict[au] = myDict.get(au, 0) + area
get() gives you the value of myDict[au], or 0 if it does not exist.
Jul 19 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3596
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two...
9
2583
by: Yaroslav Bulatov | last post by:
I made an array of 10 million floats timed how long it takes to sum the elements, here's what I got (millis): gcc -O2: 21 Python with numarray: 104 Python with Numeric: 302 java: 325 gcc: 348 Python with Psyco: 1317 Pure Python using sum: 2312
2
2251
by: SunMan | last post by:
Hello! I am trying to create a program that will ask for a user to enter a series of letters (codes) and then print out a table that shows the codes in decending frequency. Only letters will be read into the array. I have created a struct and array like below. struct record { char inputChar;
2
3333
by: Targa | last post by:
<input NAME="TAXRATE" onBlur="this.form.TAX.value = (this.form.TAXRATE.value - 0) * (this.form.ITEM1TOTAL.value - 0) + (this.form.ITEM2TOTAL.value - 0) " Size="4"> In my TAX field I get something like 1.7500000000000002. Is it possible to format this to read 1.75? Also, when summing or multiplying fields, Id like to have 4 x 2.00 = 8.00 rather than just 8.
7
2193
by: Hank | last post by:
I have a report-summing problem using Access 2000. When a section runs over the end of the page, sometimes a detail gets picked up twice. Example: Customer Header XYZ Company Detail Section (INVISIBLE) Invoice 1 $100.00 Invoice 2 $250.00 Page Break
1
9273
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
2
2463
by: MrL8Knight | last post by:
I am building a simple shopping cart and I am having problems trying to add the costs of the items to generate a total cost. I am new at this so forgive me if my technical verbiage isn’t the greatest! I am trying to sum specific values in my arrays (or the price portions of the arrays). I have tried every imaginable way with the array_sum command and nothing has worked for me! Here is what my cookie information looks like after I put 2...
12
4073
by: neeraj | last post by:
Hi Can any body give me the syntax for summing the elements of the an array , without looping thanks
7
15021
by: lethek39 | last post by:
Hey I have been trying to figure out how to sum rows and columns in a matrix square. I also have been trying to get the program to list the numbers of the diagonal in the matrix. So far this is the code I have (I am using Python): def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square import random m = {} for r in range(rows): for c in...
27
2131
by: Mark | last post by:
Hi all, I have a scenario where I have a list like this: User Score 1 0 1 1 1 5 2 3 2 1
0
10923
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...
1
11066
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
10542
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
9732
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...
0
7256
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();...
0
5943
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
6148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4778
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
3
3368
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.