[Tutor] List processing question - consolidating duplicate entries

John Fouhy john at fouhy.net
Tue Nov 27 22:59:27 CET 2007


On 28/11/2007, Richard Querin <rfquerin at gmail.com> wrote:
> I've got a list that is formatted as follows:
> [Name,job#,jobname,workcode,hours]
[...]
> Now I'd like to consolidate entries that are duplicates. Duplicates
> meaning entries that share the same Name, job#, jobname and workcode.
> So for the list above, there are 3 entries for projectA which have a
> workcode of 4001. (there is a fourth entry for projectA but it's
> workcode is 5001 and not 4001).

You use a dictionary: pull out the jobname and workcode as the dictionary key.

====
import operator

# if job is an element of the list, then jobKey(job) will be (jobname, workcode)
jobKey = operator.itemgetter(2, 3)

jobList = [...]  # the list of jobs

jobDict = {}

for job in jobList:
  try:
    jobDict[jobKey(job)][4] += job[4]
  except KeyError:
    jobDict[jobKey(job)] = job

(note that this will modify the jobs in your original list... if this
is Bad, you can replace the last line with "... = job[:]")

HTH!

-- 
John.


More information about the Tutor mailing list