Sunwoong ENFYS Cho
Sunwoong ENFYS Cho

Reputation: 23

tyring to append different items to list

this is my code

f= open("average-latitude-longitude-countries.csv", "r")
for line in f:
    line = line.strip("\n")

    elements = line.split(",")
    code = elements[0].strip('"')
    elements[1] = elements[1].strip('"')
    if len(elements) == 4:
        name = elements[1]
        latitude = float(elements[2])
        longitude = float(elements[3])
    else:
        elements[2] = elements[2].strip('"')
        name = elements[2] + elements[1]
        latitude = float(elements[3])
        longitude = float(elements[4])
    list[]
    list.append(code, name, latitude, longitude)

this csv file is as follows

AD  Andorra 42.5    1.5
AE  United Arab Emirates    24  54
AF  Afghanistan 33  65
AG  Antigua and Barbuda 17.05   -61.8
AI  Anguilla    18.25   -63.17

what i want to do is read the code, country name, latitude, longitude into

list[(code, name, lat, long)
     (code, name, lat, long)]

such format.

i've just started python and i've tried "for line in f" and read documents in appending items into list. however what i cant' seem to understand is how i add four items of different attribute into that list.

and i can't seem to understand when to use list and dictionary. dictionary is immutable? i can't seem to see the merit for this yet. and would dictionary would be better format for this?

Upvotes: 2

Views: 110

Answers (3)

Serge
Serge

Reputation: 3775

Just use the standard csv library, one day you might step on some csv perk or even, specialized library PTable if just need to prettyprint, numpy np.loadtxt for heavy data lifting etc.

https://docs.python.org/2/library/csv.html

see similar examples in the previous discussion

Python import csv to list

import csv

with open('file.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)  # Python 3

Upvotes: 0

Adhish
Adhish

Reputation: 95

You can probably use str.split()

f = open("average-latitude-longitude-countries.csv", "r")

l = []
for line in f:
    x = tuple(str(line).split())
    l.append(x)

print l

Upvotes: 2

Jan
Jan

Reputation: 43199

Don't reinvent the wheel, use a library instead, e.g. pandas:

import pandas as pd
df = pd.read_csv(your_file_here, sep='\t')

Returns a dataframe which you can access in a dict-like format.

Upvotes: 2

Related Questions