Question

So I've just started with python the last few days with nothing but some basic coding knowledge from 5 years ago. I'm in love.

I'm importing a .csv which contains historical alliances sorted by dyad...so each alliance has a special number. There are many more in the file with the same country. I'm trying to have a user give a country and a date and be able to return the countries they were in alliance with that year. Here's a row of data.

6 200 United Kingdom 255 Germany 1 1 1816 31 10 1822 1 0 1 0 0  1 0
6 200 United Kingdom 300 Austria-Hungary 1 1 1816 31 10 1822 1 0 1 0 0 1 0

First number is the dyad num, then country code and country, country code and country, day of alliance beginning, month, year, day of end, month, year. Last parts aren't really important.

import csv
name='United Kingdom'
diad = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
with open('list.csv') as inputfile:
    r = list(csv.reader(inputfile))
    for i, j in enumerate(r):
         if j == name:
              diad[0]=name
          print "true"
              diad.insert(0, name)

I run it and get nothing, so the if statement isn't true... I don't understand how though. You're looking at the first two lines of data, shouldn't enumerate find any instance of "United Kingdom" and insert what it found into the diad list? If I can make this piece work my task should be easy.

Was it helpful?

Solution

Iterating through a CSV iterates through the rows, not the columns. So in each iteration, j is a list of columns. You'd then need to iterate through the elements in j as well, in order to compare against your string.

I think you're confused about what enumerate does. You don't need it here at all, in fact. What it does is give you an index along with the value of the thing you're enumerating. So in this case, you'd get on the first iteration 0 plus the first row, then 1 with the second row, and so on. Since you're not using the index, you don't want to use enumerate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top