MarkS
MarkS

Reputation: 1539

Print values only in list of tuples to csv file

I have a small program that works, but not quite what I want.

The top half works fine.

The write (bottom) half does work, but all I am interested in is the values in the tuples. Nothing else.

My code:

import json
import csv

jsonfile = "f:\mark\python\data.json"

with open(jsonfile, "r") as jfile:
    jfile_decode = json.load(jfile)
    # Create a list of tuples with a list comprehension
    jlist = [[(k, v) for k, v in d.items() if k in ['city', 'state', 'population', 'rank']] for d in jfile_decode]
    # print(jlist)  - Just for testing to make sure the output is what I wanted -


outputfile = "f:\mark\python\data.csv"
with open(outputfile, 'w') as f:
    csv_out = csv.writer(f, delimiter=' ')
    csv_out.writerow(['city', 'state', 'population', 'rank'])
    for row in jlist:
        csv_out.writerow(row)

The output I am currently getting:

city state population rank

"('city', 'New York')" "('population', '8405837')" "('rank', '1')" "('state', 'New York')"

"('city', 'Los Angeles')" "('population', '3884307')" "('rank', '2')" "('state', 'California')"

"('city', 'Chicago')" "('population', '2718782')" "('rank', '3')" "('state', 'Illinois')"

"('city', 'Houston')" "('population', '2195914')" "('rank', '4')" "('state', 'Texas')"

What I want is this: (Just the tuple values. Nothing else)

city state population rank

'New York' 'New York' '8405837' '1'

'Los Angeles' 'California' '3884307' '2'

Upvotes: 1

Views: 571

Answers (1)

developer_hatch
developer_hatch

Reputation: 16214

You can eval the string, and get the element you want:

outputfile = "f:\mark\python\data.csv"
with open(outputfile, 'w') as f:
    csv_out = csv.writer(f, delimiter=' ')
    csv_out.writerow(['city', 'state', 'population', 'rank'])
    for row in jlist:
        csv_out.writerow(" ".join([col[1] for col in row]))

Edit To erase the double quotes inside the strings use .strip('!"'):

print(" ".join([col[1].strip('!"') for col in row]))

an example:

big_tuple = [{'city': 'New York', 'growth_from_2000_to_2013': '4.8%', 'latitude': 40.7127837, 'longitude': -74.0059413, 'population': '8405837', 'rank': '1', 'state': 'New York'},{'city': 'Los Angeles', 'growth_from_2000_to_2013': '4.8%', 'latitude': 34.0522342, 'longitude': -118.2436849, 'population': '3884307', 'rank': '2', 'state': 'California'}]

jlist = [[(k, v) for k, v in d.items() if k in ['city', 'state', 'population', 'rank']] for d in big_tuple]

for row in jlist:
    print(" ".join([col[1] for col in row]))

as result

New York 8405837 1 New York 
Los Angeles 3884307 2 California

Upvotes: 2

Related Questions