how to use dictionary - newby

Discussion in 'Python' started by GMAN1941, Jul 23, 2013.

  1. GMAN1941


    Apr 2, 2013
    Likes Received:
    huntsville, al
    using python 2.5. need help with dictionary. i know how to create it, but i can't seem to understand how to use it in a practical way. I have a set of data extracted from a database - example, States and Cities. while the state is in one field, the cities are in another field separated by comas with associated numbers (relative size)

    my code so far:

    import win32api, win32com.client
    import os, sys, string
    import csv

    f = open(file,'r')
    reader = csv.reader(f)
    # save header items
    headerList =
    dataDict = {}
    for line in reader:
    dataDict.setdefault(line[0], []).append(line[-2]) #State
    dataDict.setdefault(line[0], []).append(line[-1]) #city
    except Exception, e:

    in the dictionary i have :
    {'CA': ['Sacramento6,San Francisco4,San Diego2,Fresno5,Los Angeles1,San Jose3],'WA':['Seatle1,Tacoma3,Yakima8,Spokane2]}

    and so forth
    what i need to do (but can't quite grasp from reading the examples) is how to cycle thru each key(state), capture the associated city and plug that into a spreadsheet so that if would look like:
    Col A Col B Col C
    CA Los Angeles 1
    CA San Diego 2
    CA San Jose 3
    WA Seatle 1
    WA Spokane 2


    appologies for the newby question
    i need a point in the right direction. is this even the correct approach?

    GMAN1941, Jul 23, 2013
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.