Reputation: 115
A little bit of backstory:
I have a program that allows user to enter a Name(e.g Lisbon), and based on that User Input's country, the program will loop through my JSON file and print out all that are relevant/falls under Lisbon's Country(e.g. Jade, John).
Here's my JSON file:
{
"user1":{
"Country":[
"China",
"USA",
"Nepal"
],
"Name":[
"Lisbon"
]
},
"user2":{
"Country":[
"Sweden",
"China",
"USA"
],
"Name":[
"Jade"
]
},
"user3":{
"Country":[
"India",
"China",
"USA"
],
"Name":[
"John"
]
}
}
I'm new to Python and I would like to know how do I export my printed results and at the same time format it nicely onto the CSV file, this is my printed results:
Jade : Sweden, China, USA
John : India, China, USA
This is how I would like it to look in the CSV file:
Name Country
Jade Sweden, China, USA
John India, China, USA
This is what I've done so far:
def matchCountry():
userName = raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
print (v['Name'][0] + " : " + ", ".join(v['Country']))
with open('output.csv', 'ab') as csvfile:
csvwriter = csv.writer(csvfile)
for row in result.items():
csvwriter.writerow(row)
Upvotes: 0
Views: 2318
Reputation: 512
tested for Python 3.6.7
# -*- coding: utf-8 -*-
import json
import os
def matchCountry():
userName = input("Enter user's name: ")
with open('list_of_users.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
results = []
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
r = v['Name'][0] + "\t" + ", ".join(v['Country'])
print(r)
results.append(r)
if not os.path.exists('output.csv'):
with open('output.csv', 'w') as csvfile:
csvfile.write("Name\tCountry\n")
with open('output.csv', 'a') as csvfile:
for row in results:
csvfile.write(row + "\n")
def main():
matchCountry()
if __name__ == '__main__':
main()
Upvotes: 0
Reputation: 115
I did this instead, correct me if this is bad coding or not!
with open('output.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile, f, lineterminator='\n')
csvwriter.writerow(["Name", "Country"])
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
csvwriter.writerow([v['Name'][0], ", ".join(v['Country'])])
And this is my output in the CSV file:
Name Country
Jade Sweden, China, USA
John India, China, USA
Upvotes: 0
Reputation: 2580
There are many ways to do this but you could consider storing the data in a pandas dataframe and then writing the data to a .csv.
For example,
import pandas as pd
df = pd.DataFrame({'Names':['John','Jane'],
'Countries':[['Spain','India','USA'],['China','Spain','India']]})
df.to_csv('filepath_to_save',index=False)
This writes:
Countries,Names
"[Spain,India,USA]",John
"[China,Spain,India]",Jane
The disadvantage of this is because you have multiple values for a single column, it does not save in the most appealing format. If you knew persons would only, say, have three or less countries you could do:
df = pd.DataFrame({'Names':['John','Jane'],
'Country_one':['Spain','China'],
'Country_two':['India','Spain'],
'Country_three':['USA','India']})
# save to .csv ordering the columns
df.to_csv('filepath_to_save',index=False, header=True,
columns=["Names","Country_one","Country_two","Country_three"])
which writes:
Names,Country_one,Country_two,Country_three
John,Spain,India,USA
Jane,China,Spain,India
This will then save in a nice .csv format, but with the disadvantage of multiple
Upvotes: 1