Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How would I set the dict[value] to correspond to its dict[key] where the value itself is a dictionary?

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 469
    Answer it

    How would I set the dict[value] to correspond to its dict[key]  where the value itself is a dictionary ? 

    I have a csv file where I am trying to count row[3] then connect it with row[0]

         row[0]      row[3]
         'A01'          'a'
         'B02'          'a'
         'A01'          'b'
         'A01'          'a'
         'B02'          'a'
         'A01'          'a'

    so that in the end it should be 

         {'A01':{a:3, b:1}, 'B02':{a:2}}

     

    I have this code so far:

    d = {'job': {'general_types': 0}}
        d['job'] ={}
        d['general_types'] ={}
        with open("sample.csv", "r") as data1:
            outcome_reader = csv.reader(data1)
            for rows in outcome_reader:
                d['job'].setdefault(rows[0])
                d['general_type'].setdefault(rows[3],0)
                d['general_type'][rows[3]] += 1
        print d


    but so far I'm getting 

         {'job'{'A01':None, 'B02': None {a:5, b:1}} 

 1 Answer(s)

  • Hi Paola Santiago, use this concept you have to connect with row.

    reader = csv.DictReader(open('C:\\Users\\Shiva\\Desktop\\demo.csv'))
    
    result = {}
    
    for row in reader:
        for column, value in row.items():
            result.setdefault(column, []).append(value)
            print('Column -> ', column, '\nValue -> ', value)
    print(result)
    
    fieldnames = result.keys()
    
    csvwriter = csv.DictWriter(open('C:\\Users\\Shiva\\Desktop\\Demo_out.csv', 'w'), delimiter=',', fieldnames=result.keys())
    
    csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
    
    for row in result.items():
        print('Values -> ', row)
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: