[Tutor] renaming files within a directory

Tim Golden mail at timgolden.me.uk
Sun Jul 26 21:41:10 CEST 2009


davidwilson at Safe-mail.net 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


More information about the Tutor mailing list