Please Help, Appending into list problem!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mizukage
    New Member
    • Apr 2010
    • 2

    Please Help, Appending into list problem!

    I figured out the answer myself and no longer need this post.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Ok, so lets say I have a .csv file called flags.csv, with the following data

    (Column 1)- (Column 2)
    Country- Colour
    Australia- Red
    Australia- Red
    Australia- Red
    America - Red
    UK - Red
    Japan- Red
    China - Red
    Australia- White
    America - White
    UK - White
    Japan - White
    Australia -Blue
    America - Blue
    UK - Blue
    China - Yellow


    I would like to arrange this data so as to present the countries with flags of at least three colours, and the total number of colours they have. I want the output to end up in this format.
    Column1-Column2-Column3-Column4-Column5
    --------- Blue - Red - White - Yellow - Total
    America-- 1 - 3 - 1 - 0 - 5
    Australia- 1 - 1 - 1 - 0 - 3
    UK------- 1 - 1 - 1 - 0 - 3



    I have no idea what the formulas for manipulating the data so as it forms in this way are. Could you please give me some help?

    Thank you.
    Compile the data into a dictionary. From there you can extract the data you need and convert to another format if needed.
    Code:
    data = """Country- Colour
    Australia- Red
    Australia- Red
    Australia- Red
    America - Red
    UK - Red
    Japan- Red
    China - Red
    Australia- White
    America - White
    UK - White
    Japan - White
    Australia -Blue
    America - Blue
    UK - Blue
    China - Yellow"""
    
    dataList = data.split("\n")[1:]
    dd = {}
    for item in dataList:
        country, color = [s.strip() for s in item.split("-")]
        dd.setdefault(country, []).append(color)
    
    print
    print "   Country: Blue  Red  White Yellow Total"
    
    for country in dd:
        print "%10s:%5s%5s%5s%5s%5s" % (country,
                                        dd[country].count("Blue"),
                                        dd[country].count("Red"),
                                        dd[country].count("White"),
                                        dd[country].count("Yellow"),
                                        len(dd[country]))
    The output:
    Code:
    >>> 
       Country: Blue  Red  White Yellow Total
         Japan:    0    1    1    0    2
     Australia:    1    3    1    0    5
         China:    0    1    0    1    2
       America:    1    1    1    0    3
            UK:    1    1    1    0    3
    >>>

    Comment

    Working...