Python programming: Reading file, splitting and stripping variables and creating dictionary

32 Views Asked by At

i have data like this

AL, Alabama, Montgomery, 4447100, 
AK, Alaska, Juneau,  626932,  
AZ, Arizona,  Phoenix, 5130632,        
AR, Arkansas, Little Rock, 2673400, 
CA, California,  Sacramento, 33871648, 
CO, Colorado,   Denver,  4301261, 
CT, Connecticut,  Hartford, 3405565, 
DE, Delaware, Dover,  783600,    
DC, District of Columbia,  Washington, 572059,  
FL, Florida,    Tallahassee, 15982378,

I keep getting errors like can not iterate and I can’t figure out how to strip and split this into a dictionary.

I have tried:

        for line in f:
           final += line.strip().split(',')
           count+=1
           print('Line{}: {}'.format(count, line.strip().split(',')))
           del final[-1]
        print(final)
        newDict = {}
        for i in final:
            finalx += i.strip(' ')
        print(finalx)
        for i in range(0, len(final), 4):
            newDict[final[i]] = final[i+1, i+2, int(i+3)]
        print(newDict)]

but it says something tuples can not be in the definition. I am expecting to create a dictionary then create a csv file from that and a json file from the dictionary created.

1

There are 1 best solutions below

1
ddjerqq On

for starters, try this code

with open("path/to/file.txt", "r", encoding="utf-8", errors="ignore") as f:
    data = []
    for line in f:
        code, state, name, population = line.split(", ")
        data.append((code, state, name, int(population)))

to load the data

with open is a context manager, it closes the file for you automatically once you're done working with it.

other than this, the code should be pretty straight forward.

after you load the file content into a list, you should be able to manipulate it to however you want easily.

you can even use a dict-comprehension like so:

dict_data = {
    code: (state, name, population)
    for code, state, name, population in data
}