[email protected] wrote:
OK I am lost ;(

I changed the code to:

reader = csv.reader(open("countries.csv"),  delimiter=";")
for row in reader:
... print row ... ['bi', 'Burundi']
['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:

dic = []
for row in reader:
...         newdic.append({row[0]: row[1]})
...
dic
[]

I get an empty dictionary

Well, you actually get an empty list :)
To instantiate an empty dictionary, you use curly brackets:

d = {}

To add something to a dictionary, you use:

d[<key>] = <value>

Try something like this:

<code - untested>
import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = {} # note the curly brackets
for row in reader:
  code, name = row # handy Python tuple unpacking
  countries[name] = code

</code>


Once you're used to the idea, you can get reasonably slick
with dictionary initialisers and generator expressions:

import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = dict ((row[1], row[0]) for row in reader)

And once you're really confident (and if you're a
fan of one-liners) you can get away with this:

import csv
countries = dict (
  (name, code) for \
    (code, name) in \
    csv.reader (open ("countries.csv"), delimiter=";")
)


BTW, I tend to open csv files with "rb" as it seems to
avoid line-ending issues with the csv module. YMMV.

TJG
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to