Search code examples
pythonexcelfwrite

How can I create dictionary within dictionary


I have the below code:

datedict = defaultdict(set)
with open('d:/info.csv', 'r') as csvfile:
    filereader = csv.reader(csvfile, 'excel')

    #passing the header
    read_header = False
    start_date=date(year=2009,month=1,day=1)
    #print((seen_date - start_date).days)
    tdic = {}
    for row in filereader: 
        if not read_header:
            read_header = True
            continue

# reading the rest rows
        name,id,firstseen = row[0],row[1],row[3]
        try:
            seen_date = datetime.datetime.strptime(firstseen, '%d/%m/%Y').date()               
            deltadays = (seen_date-start_date).days
            deltaweeks = deltadays/7 + 1
            key = name +'-'+id
            currentvalue = tdic.get(key, [])
            currentvalue.append(deltaweeks)
            tdic[key] = currentvalue

        except ValueError:
            print('Date value error')
            pass

tdic = dict((name, max(weeks) - min(weeks) + 1) for name, weeks in tdic.iteritems())

pprint.pprint(tdic)

in which I get the below result:

{'Mali-2': 20,
 'Gooki-3': 6,
 'Piata-4': 6,     
 'Goerge-5': 4,
 'Samoo-6': 1,
 'Marria-7': 2}

Now I would like to write and print the three items, name,id and weeks as separate columns in an excel file. Anyone knows how it is possible?


Solution

  • >>> with open('out.csv', 'w') as f:
            w = csv.writer(f)
            for k, v in tdic.iteritems():
                name, id_ = k.split('-')
                weeks = v
                w.writerow([name, id_, weeks])
    
    
    >>> with open('out.csv') as f:
            print f.read()
    
    
    Piata,4,6    
    Mali,2,20    
    Goerge,5,4    
    Gooki,3,6    
    Samoo,6,1    
    Marria,7,2
    

    I however don't like the way you have done this, here are some suggestions for your code:

    key = name +'-'+id
    

    Instead of using string manipulation to create a key, use a tuple:

    key = (name, id)
    

    Change this line:

    tdic = dict((name, max(weeks) - min(weeks) + 1) for name, weeks in tdic.iteritems())
    

    to just say

    tdic = dict((key, max(weeks) - min(weeks) + 1) for key, weeks in tdic.iteritems())
    

    since now it is a key of (name, id_) we should reflect that (it's a minor thing but important)

    Then the above code would simply be

    >>> with open('out.csv', 'w') as f:
            w = csv.writer(f)
            for (name, id_), weeks in tdic.iteritems():
                w.writerow([name, id_, weeks])