Why give this error while writing to csv file ???
When I user csv.writer at that time code run perfectly but can not get header give me some suggestion and solution for this
AttributeError: 'list' object has no attribute 'keys'
import random
import csv
BloodGroup = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']
City = ['Ahmedabad', 'Gandhinagar', 'Vadodara', 'Rajkot', 'Surat']
Month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
ForWhat = ['anemia','cancer','hemophilia','kidney disease','liver disease','severe infection','sickle cell disease','thrombocytopenia']
bloodgroup = random.choice(BloodGroup)
city = random.choice(City)
if city == 'Ahmedabad':
area = random.choice(['Gota', 'Maninagar', 'Bopal', 'Satellite', 'Bodakdev', 'Thaltej', 'Chandkheda', 'Prahlad Nagar', 'SG Highway'])
elif city == 'Gandhinagar':
area = random.choice(['Sargaasan', 'Urjanagar', 'Kudasan', 'Zundal', 'Raysan', 'Shantigram'])
elif city == 'Vadodara':
area = random.choice(['Alkapuri', 'Akota', 'Fatehgunj', 'Waghodia'])
elif city == 'Rajkot':
area = random.choice(['Mota Mava', 'Kalawad', 'Bhakti Nagar', 'Madhapar'])
else:
area = random.choice(['Sayan', 'Ghod Dod', 'Pal', 'Vesu'])
bloodquantity = random.randint(0,4)
month = random.choice(Month)
year = random.randint(2015, 2019)
forwhat = random.choice(ForWhat)
personcount = random.randint(0,10)
print(f'{bloodgroup} {city} {area} {bloodquantity} {month} {year} {forwhat} {personcount}')
data = [bloodgroup, city, area, bloodquantity, month, year, forwhat, personcount]
print('Data:',data)
with open('BloodBankDataSet.csv', 'w') as new_file:
fieldname = ['Bloodgroup', 'City', 'Area', 'Bloodquantity', 'Month', 'Year', 'ForWhat', 'PersonCount']
csv_writer = csv.DictWriter(new_file, fieldnames= fieldname)
csv_writer.writeheader()
csv_writer.writerow(data)
DictWriter expects a dictionary as the parameter and you're passing a list.
Consider using this:
csv_writer.writerow({k: v for k,v in zip(fieldname, data)})
Related
Right now I am working on a file where it lets you customise a password. Each section lets you choose between a name, number, and more with a certain amount of sections. I can't figure out how to place the code that generates each section in the num_of_pass for loop without repeating the text
'What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) '
each time it gives a new password. How could I make this work?
names = ['Tim', 'Alex', 'Thomas', 'Katrina', 'Joshua', 'James', 'John', 'Emily', 'Mary', 'Patricia', 'Jennifer',
'Linda', 'Elizabeth', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Ashley', 'Damon', 'Max']
options = ['name', 'number', 'letter', 'symbol', 'year', 'day', 'month']
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
sections = input('How many sections would you like? ')
num_of_pass = input('How many passwords would you like? ')
current_section = 1
for num in range(int(sections)):
section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
if section_type == 'name':
section = random.choice(names)
elif section_type == 'number':
section = str(random.randint(1, 9))
elif section_type == 'letter':
section = random.choice(string.ascii_letters)
elif section_type == 'symbol':
section = str(random.choice(string.punctuation))
elif section_type == 'year':
section = str(random.randint(1000, 2020))
elif section_type == 'day':
section = random.choice(days)
elif section_type == 'month':
section = random.choice(months)
password = password + section
current_section += 1
print(password)
password = ''
I think you can simply put the input statement outside of the loop, or there's a work around it - put it in a condition:
for num in range(int(sections)):
if count == 0:
section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
count += 1
if section_type == 'name':
section = random.choice(names)
im using Python and it seems that I have an issue with my for loop.
So here are the data sets that I am working with:
A) I have this csv file, that contains all the car data
B) I have also the Brand to Car (type) in csv that looks like below
What I need to build is to build another CSV that breaks down each line into its correct brand and car type. while making sure that it is accurate (for example there is Camry L and Camry LE - sometimes it pulls both).
This is the output that I am looking for:
So far here is my script:
temp_car_list = []
reader_type = csv.DictReader(type_library)
with open(file_name) as Output_file:
reader = csv.DictReader(Output_file)
for row in reader:
Title = row ["Item Name"]
print (Title)
for brand in brand_library_iterate:
if brand in Title:
Brand_Name = brand
print(Brand_Name)
#Get Type Library List
for Car_type in reader_type:
Brand_String = str(Brand_Name)
print(Brand_String)
type_list = temp_car_list.append(Car_type[Brand_String])
print(temp_car_list)
for car_type in temp_car_list:
if car_type in Title:
car_type_output = car_type
print (car_type_output)
temp_car_list.clear()
Logic of the script:
1)Pull Title (e.g. Black Toyota Camry L)
2)Pull The brand of the car from a list
3)From output #2 - map into #B (the csv file in the picture)
Here is what I get (unfortunately):
What I have noticed to be the main issue:
1) for some reason the Brand_Name does not change in accordance to the second or subsequent rows. So it is stuck at Toyota.
2) The car_type_output pulls out both Camry L and Camry LE
Question: Break down each line into its correct brand, color and car type.
A = """Item Name
Black Toyota Camry L
Honda Accord Navy
Grey Toyota Corolla
Black Nissan Murano
Silver Toyota Camry LE
"""
B = """Toyota,Nissan,Honda
Camry L,Murano,Accord
Corolla,Rogue,Civic
Avalon,Pathfinder,CR-V
Highlander,Maxima,HR-V
Prius,Altima,
Camry LE,,
"""
The simplest approach by spliting the lines from file A.
From file B only the first line with the brands are used to detect the out of order line:
Honda Accord Navy.
import io
def simple_split_title():
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
brands = fh.readline().rstrip().split(',')
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
item = title.split(' ')
if item[0] in brands:
_color, _brand, _type, _last = len(item) - 1, 0, 1, len(item) - 1
else:
_color, _brand, _type, _last = 0, 1, 2, len(item)
result = {'title': title,
'brand': item[_brand],
'color': item[_color],
'type': ' '.join(item[_type:_last])}
print(result)
The most expensive approach. This requires to loop the dict from file B twice per line from file A.
To detect the out of order line: Honda Accord Navy, two string comparson required.
import io, csv
def looping_dict():
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
car_type = [_dict for _dict in csv.DictReader(fh)]
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
result = {'title': title, 'brand': '', 'color': '', 'type': ''}
# Get brand
for brand in car_type[0].keys():
if brand in title:
result['brand'] = brand
title = title.replace(brand + ' ', '')
break
# Get type
for _type in car_type:
if title.endswith(_type[brand]) or title.startswith(_type[brand]):
result['type'] = _type[brand]
title = title.replace(_type[brand], '')
break
# Get color
result['color'] = title.strip()
print(result)
The mathematical approach, using theory of sets.
The list of car_type is only looped once per line of file A.
A extra condition to detect the out of order line: Honda Accord Navy, is not required.
You get a match, if the set of title items are a superset of car_type[x].set.
import io, csv
from collections import namedtuple
def theory_of_sets():
CarType = namedtuple('CarType', 'set brand type')
car_type = []
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
for _dict in csv.DictReader(fh):
for brand, _type in _dict.items():
_set = {brand} | set(_type.split(' '))
car_type.append(CarType._make((_set, brand, _type)))
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
_title = title.split(' ')
_items = set(_title)
result = None
for ct in car_type:
if _items.issuperset(ct.set):
result = {'title': title,
'brand': ct.brand,
'color': (_items - ct.set).pop(),
'type': ct.type}
break
print(result)
Output: All three examples print the same output.
{'title': 'Black Toyota Camry L', 'brand': 'Toyota', 'color': 'Black', 'type': 'Camry L'}
{'title': 'Honda Accord Navy', 'brand': 'Honda', 'color': 'Navy', 'type': 'Accord'}
{'title': 'Grey Toyota Corolla', 'brand': 'Toyota', 'color': 'Grey', 'type': 'Corolla'}
{'title': 'Black Nissan Murano', 'brand': 'Nissan', 'color': 'Black', 'type': 'Murano'}
{'title': 'Silver Toyota Camry LE', 'brand': 'Toyota', 'color': 'Silver', 'type': 'Camry LE'}
I want to run this code but I have some errors and I can't see the problem. The code is below. And do I have to set global list for cities, month and the day?
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = get_user_input('Now you have to enter a month to get some months result) \n> ', months)
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]
day = get_user_input('Now you have to enter a month to get some months result) \n> ', days)
print('-'*40)
return city, month, day
If I understood you correctly I think this is what you have to do:
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').capitalize() #was lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = input('Now you have to enter a month to get some months result \n> {} \n> '.format(months))
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = input('Now you have to enter a dau to get some days result \n> {} \n> '.format(days))
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
A couple of things to note:
The input of the city was set to '.lower()' while the list of cities contained capitilized letters. So I changed it to capitilize().
Also you wanted it to return every day and month if the user didn't specify any input. Therefore I added a simple if-test at the end to check for that. Furthermore I used the '-format()' to display the different options the user has on the input. Hope everything is clear!
Using .lower() is fine, but you should change your cities list and your `CITY_DATA`` dict to match the names (so New York City --: new york).
CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('chicago', 'new york', 'washington')
while True:
city = raw_input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = raw_input('Now you have to enter a month to get some months result \n> {} \n>'.format(months)).lower()
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = raw_input('Now you have to enter a day to get some days result \n> {} \n>'.format(days)).lower()
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
If you are using Python 2.7, you should use raw_input() instead of input().
I'm new to python and I was trying to create an error handling for multiple users input. I made the code as the following.
`
#load and filter dataset
import pandas as pd
CITY_DATA = {'Chicago' : 'chicago.csv',
'New York City':'new_york_city.csv',
'Washington':'washington.csv'}
#filtering dataset
def get_filters ():
city_options = ['Chicago','New York City','Washington'.title()]
month_options = ['January','February','March','April','May','June','July','August','September','November','December','all'.title()]
day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','all']
while True:
city = input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'.title())
if city in city_options :
break
else:
print('Your choice is not available. Please try again')
while True:
month = input('\nInsert month to filter by or "all" to apply no month filter! (January, February, etc.)\n'.title())
if month in month_options :
break
else:
print('Your choice is not available. Please try again')
while True:
day = input('\nInsert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.)\n'.title())
if day in day_options :
break
else:
print('Your choice is not available. Please try again')
return city, month, day
But I believe there is a simpler way for this or maybe create a function? Any help would be greatly appreciated!
You can use the try/except statements and loop once for all of three inputs instead of looping again and again. Here is what I came up with. If it doesn't help, happy to delete it.
def get_filters():
city_options, month_options, day_options = ['Chicago','New York City','Washington'.title()], ['January','February','March','April','May','June','July','August','September','November','December','all'.title()], ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','all'.title()]
while True:
try:
city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'.title()))
month = month_options.index(input('\nInsert month to filter by or "all" to apply no month filter! (January, February, etc.)\n'.title()))
day = day_options.index(input('\nInsert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.)\n'.title()))
return city_options[city], month_options[month], day_options[day]
except ValueError:
print ("Your previous choice is not available. Please try again")
print (get_filters())
A little refactored version of your solution. Not sure whether this is of huge help.
def get_valid_input(input_msg, options):
while True:
entered_value = input(input_msg)
if entered_value in options:
break
else:
print('Your choice is not available. Please try again')
continue
def get_filters():
city_options = ['Chicago', 'New York City', 'Washington'.title()]
month_options = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November',
'December', 'all'.title()]
day_options = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'all']
city_input_msg = 'Insert name of the city to analyze! (Chicago, New York City, Washington): '
get_valid_input(city_input_msg, city_options)
month_input_msg = 'Insert month to filter by or "all" to apply no month filter! (January, February, etc.): '
get_valid_input(month_input_msg, month_options)
day_input_msg = 'Insert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.): '
get_valid_input(day_input_msg, day_options)
return city, month, day
This is my first time working with python. I'm trying to create a dictionary for each county (23 in total) with year as the key for population and income values. Strong arming the code seems to work, but I'm sure there is an easier way to do it using loops or classes...any suggestions?? Thanks!!!!!
import xlrd
wb= xlrd.open_workbook('C:\Python27\Forecast_test.xls')
popdata=wb.sheet_by_name(u'Sheet1')
incomedata=wb.sheet_by_name(u'Sheet2')
WyomingCnty =('Albany', 'Big Horn',
'Campbell', 'Carbon', 'Converse',
'Crook', 'Fremont', 'Goshen',
'Hot Springs','Johnson', 'Laramie',
'Lincoln', 'Natrona','Niobrara',
'Park', 'Platte', 'Sheridan', 'Sublette',
'Sweetwater', 'Teton', 'Uinta', 'Washakie', 'Weston','Wyoming')
Years = ('y0','y1','y2','y3','y4','y5','y6','y7','y8','y9','y10',
'y11','y12', 'y13', 'y14', 'y15', 'y16', 'y17', 'y18','y19',
'y20','y21','y22','y23','y24','y25','y26','y27','y28','y29','y30')
AlbanyPop = popdata.col_values(colx=1,start_rowx=1,end_rowx=None)
AlbanyIncome= incomedata.col_values(colx=1,start_rowx=1,end_rowx=None)
AlbanyDict1=dict(zip(Years,AlbanyPop))
AlbanyDict2=dict(zip(Years,AlbanyIncome))
BigHornPop = popdata.col_values(colx=2,start_rowx=1,end_rowx=None)
BigHornIncome= incomedata.col_values(colx=2,start_rowx=1,end_rowx=None)
BigHornDict1=dict(zip(Years,BigHornPop))
BigHornDict2=dict(zip(Years,BigHornIncome))
popdict = {}
incdict = {}
for ix, city in enumerate(WyomingCnty):
popdict[city] = dict(zip(Years, popdata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)
incdict[city] = dict(zip(Years, incomedata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)
I would just use another dictionary. As in:
import xlrd
wb= xlrd.open_workbook('C:\Python27\Forecast_test.xls')
popdata=wb.sheet_by_name(u'Sheet1') #Import population data
incomedata=wb.sheet_by_name(u'Sheet2') #Import income data
WyomingCnty =('Albany', 'Big Horn',
'Campbell', 'Carbon', 'Converse',
'Crook', 'Fremont', 'Goshen',
'Hot Springs','Johnson', 'Laramie',
'Lincoln', 'Natrona','Niobrara',
'Park', 'Platte', 'Sheridan', 'Sublette',
'Sweetwater', 'Teton', 'Uinta', 'Washakie', 'Weston','Wyoming')
Years = ('y0','y1','y2','y3','y4','y5','y6','y7','y8','y9','y10',
'y11','y12', 'y13', 'y14', 'y15', 'y16', 'y17', 'y18','y19',
'y20','y21','y22','y23','y24','y25','y26','y27','y28','y29','y30')
county_dict = {}
for col, county in enumerate(WyomingCnty):
county_dict[county] = {}
county_popdata = popdata.col_values(colx=col, start_rowx=1, end_rowx=None)
county_incdata = incomedata.col_values(colx=col, start_rowx=1, endrowx=None)
county_dict[county]['population'] = county_popdata
county_dict[county]['income'] = county_incdata
county_dict[county]['pop_by_year'] = dict(zip(Years, county_popdata))
county_dict[county]['inc_by_year'] = dict(zip(Years, county_incdata))