Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8985271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T21:17:40+00:00 2026-06-15T21:17:40+00:00

Update: The Solution I managed to get the following code to work import collections

  • 0

Update: The Solution

I managed to get the following code to work

import collections
from lxml import etree
## Up here is code for getting an .xml input file from the user, opening that file, etc. ##
## This part is in a for loop that goes over each order in the xml file ##
## This all would have an extra indent because it is under this: for order in root.xpath('//order'): ##
itemlist = []
    ## This part looks through the .xml file for the order it is currently iterating and puts the items into a list ##
    for element in order.iter('items'):
        itemlist.append ("%s" % str.upper((element.get('type'))))
    ## This part 'sanitizes' the order name from the .xml file for use as a key ##
    for element in order.iter('order'):
        ordername = element.get('name')
        strippedordername = re.sub('[/\()!@#$%^&*()]', '', ordername)
        allordernames.append (strippedordername)
        print strippedordername
        #print itemlist
        ## This bit compiles a shopping list of items in a special dict subclass called a Counter. ##
        ordercounter.update(itemlist)
        ## This part makes a dict with order names for its keys and their corresponding Counter of items as its values ##
        ordersdictsdict[strippedordername] = collections.Counter(itemlist)
zeros = dict((k,0) for k in ordercounter.keys())
for cntr in ordersdictsdict.values():
    cntr.update(zeros)

#print ordercounter
#print ordersdictsdict
key_order = list(ordercounter.keys())
print key_order
with open(out_file,'w') as fout:
    fout.write('Order,'+','.join(key_order)+'\n')
    fout.write('Totals,'+','.join(str(ordercounter[k]) for k in key_order)+'\n') 
    for ordername,dct in ordersdictsdict.items():
        fout.write(ordername+','+','.join(str(dct[k]) for k in key_order)+'\n')
fout.closed

The output ends up looking like this:

Order,Spam,Eggs,Baked Beans,Sausage
Totals,13,1,1,1
Order for Joe,2,1,0,1
Order for Jill,11,0,1,0

What I Have

My script takes an input xml file and parses it, looking for order name and then order contents. There can be multiple orders in one xml file. I then have a counter that tallies up all the items from all the orders and gives me a grand total shopping list.

Given these two sample orders:

Order for Joe: Spam, Egg, Sausage, Spam
Order for Jill: Spam, Spam, Spam, Spam, Spam, Spam, Spam, Beaked Beans, Spam, Spam, Spam, Spam

The counter would look like this:
Counter({'Spam': 13,'Baked Beans' 1, 'Egg': 1, 'Sausage': 1})

I then write this to a csv file so that it looks like this:

Item,Count
Spam,13
Baked Bean,1
Egg,1
Sausage,1

What I Want

While the grand total shopping list is nice, I’d like to expand my output csv file to also include a shopping list for each order name. I don’t care if order names are the rows or the columns. I also don’t really care if the cell for an item not in that order is a 0 or empty but I’ll use 0 in my examples.

Example Desired Output with Order Names as Rows

Order Name,Spam,Baked Beans,Egg,Sausage
Totals,13,1,1,1
Order for Joe,2,0,1,1
Order for Jill,11,1,0,0

Example Desired Output with Order Names as Columns

Item,Totals,Order for Joe,Order for Jill
Spam,13,2,11
Baked Beans,1,0,1
Egg,1,1,0
Sausage,1,1,0

Notes

I want this script to work on any input file – of course if the input only contains one order, then Totals will match that order name. I have to first make a grand total counter (so that I have all the possible items for the order(s) in question) and then fill in the csv with counts from each order. In other words, I can’t start my csv file by writing the items to it hard coded because the next input file might have different items in the orders.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T21:17:41+00:00Added an answer on June 15, 2026 at 9:17 pm

    Why can’t you use a Counter for every line of the input file?

    from collections import Counter
    d = {}  
    #*1* Alternatively, could use : d = defaultdict(Counter)
    with open(inputfile) as input_file:
        for line in input_file:
            for_who, items = line[:-1].split(':',1)
            d[for_who] = Counter(items.split(','))  
            #Alternatively, if using defaultdict at *1*, d.update(items.split(','))
            #This allows "joe" to register multiple shopping lists which get summed into 1
    
    #get totals by `sum`ming your Counters values:
    totals = sum(d.values())
    
    #Now add a 0-dict to each of the dictionaries just to make sure they have all the keys
    zeros = dict((k,0) for k in totals)
    for cntr in d.values():
        cntr.update(zeros)
    
    key_order = list(totals.keys())  #list for py2k
    with open(output_file,'w') as fout:
        fout.write('Order '+','.join(key_order)+'\n')
        fout.write('Totals,'+','.join(str(totals[k]) for k in key_order)+'\n') 
        for person,dct in d.items():
            fout.write(person+','+','.join(str(dct[k]) for k in key_order)+'\n') 
    

    You may need to get a little more tricky to deal with quoting if your items can have commas in the names (Think csv module for that stuff), but this should give you a good place to start.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Update: This question was an epic failure, but here's the working solution. It's based
Update I've managed to get around this. Now I check myself, whether the dependency
Update Solution Found See Bottom of post if interested Seems simple enough and for
I am not interested in any auto update solution, such as ClickOnce or the
[UPDATE] the clean goal runs smoothely all over the projects of the solution, the
Update: I've added an answer that describes my final solution (hint: the single Expr
NOTE: I added my new solution at the UPDATE answer below. I try to
Possible Duplicate: SQL ORDER BY total within GROUP BY UPDATE: I've found my solution,
I have code like the following, class _Process(multiprocessing.Process): STOP = multiprocessing.Manager().Event() def __init__(self, queue,
Update take 2 here is the two queries i'm working with (paging is omitted

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.