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().
Related
I am trying to run the following code:
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
while True:
city = input('Which city you would like to explore : "chicago" , "new york city" , or "washington" :' )
if city not in ('chicago', 'new york city', 'washington'):
print(" You entered wrong choice , please try again")
continue
else:
break
# get user input for month (all, january, february, ... , june)
while True:
month = input('Enter "all" for all data or chose a month : "january" , "february" , "march", "april" , "may" or "june " :')
if month not in ("all", "january", "february", "march", "april", "may", "june"):
print(" You entered wrong choice , please try again")
continue
else:
break
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input('Enter "all" for all days or chose a day : "saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday": ')
if day not in ("all","saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"):
print(" You entered wrong choice , please try again")
continue
else:
break
print('-'*60)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(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
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month , day of week , and hour from Start Time to new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the month_list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
popular_month = df['month'].mode()[0]
print('\n The most popular month is : \n', popular_month)
# display the most common day of week
popular_day = df['day_of_week'].mode()[0]
print('\n The most popular day of the week is : \n', str(popular_day))
# display the most common start hour
popular_hour = df['hour'].mode()[0]
print('\n The most popular hour of the day is :\n ', popular_hour)
print("\nThis took %s seconds.\n" % (time.time() - start_time))
print('-'*60)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
start_station = df['Start Station'].value_counts().idxmax()
print('\n The most commonly used start station is : \n', start_station)
# display most commonly used end station
end_station = df['End Station'].value_counts().idxmax()
print('\nThe most commonly used end station is: \n', end_station)
# display most frequent combination of start station and end station trip
combination = df.groupby(['Start Station','End Station']).value_counts().idxmax()
print('\nThe most frequent combination of start station and end station are: \n', combination)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
start_time = time.time()
travel_time = sum(df['Trip Duration'])
print('Total travel time:', travel_time / 86400, " Days")
# display total travel time
total_time = sum(df['Trip Duration'])
print('\nThe total travel time is {} seconds: \n', total_time)
# display mean travel time
mean_time = df['Trip Duration'].mean()
print('\n The average travel time is \n', mean_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
#print(user_types)
print('User Types:\n', user_types)
# TO DO: Display counts of gender
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
and I am receiving the following errors , can someone assist please
the errors:
> Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\indexes\range.py", line 391, in get_loc
return self._range.index(new_key)
^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 203, in <module>
main()
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 192, in main
time_stats(df)
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 100, in time_stats
popular_month = df['month'].mode()[0]
~~~~~~~~~~~~~~~~~~^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\series.py", line 981, in __getitem__
Calculating The Most Frequent Times of Travel...
return self._get_value(key)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\series.py", line 1089, in _get_value
loc = self.index.get_loc(label)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\indexes\range.py", line 393, in get_loc
raise KeyError(key) from err
KeyError: 0
I am expecting to filter pandas DataFrame to return month, day of week, and hour to perform some statistics.
KeyError means that the key isn't valid, because it doesn't exist. In this case, one reason to get KeyError when trying to get first mode is when column 'month' in dataframe is empty, and therefore mode() returns an empty collection, so you get KeyError: 0 when trying to get its first element.
To avoid this, you could replace:
popular_month = df['month'].mode()[0]
With:
try:
# try to get first mode of column 'month'
popular_month = df['month'].mode()[0]
except KeyError:
# if there's no data on column 'month'
popular_month = "unknown"
Because if there's no data on 'month' column, there's no point in trying to get its mode.
More about handling exceptions: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Also when I tried to ( not use the filters) by choosing " all " in the second and 3rd input, I get the following result:
Calculating The Most Frequent Times of Travel...
The most popular month is :
6
The most popular day of the week is :
<bound method PandasDelegate._add_delegate_accessors.._create_delegator_method..f of <pandas.core.indexes.accessors.DatetimeProperties object at 0x0000022B7CD5E890>>
The most popular hour of the day is :
17
This took 0.0260775089263916 seconds.
Calculating The Most Popular Stations and Trip...
The most commonly used start station is :
Streeter Dr & Grand Ave
The most commonly used end station is:
Streeter Dr & Grand Ave
The most frequent combination of start station and end station are:
('2112 W Peterson Ave', '2112 W Peterson Ave', 1064651, Timestamp('2017-06-02 07:59:13'), '2017-06-02 08:25:42', 1589, 'Subscriber', 'Female', 1963.0, 6, <bound method PandasDelegate._add_delegate_accessors.._create_delegator_method..f of <pandas.core.indexes.accessors.DatetimeProperties object at 0x0000022B7CD5E890>>, 7)
This took 2.1254045963287354 seconds.
Total travel time: 3250.8308680555556 Days
The total travel time is {} seconds:
280871787
The average travel time is
936.23929
This took 0.06502270698547363 seconds.
Calculating User Stats...
User Types:
Subscriber 238889
Customer 61110
Dependent 1
Name: User Type, dtype: int64
This took 0.022009611129760742 seconds.
Would you like to restart? Enter yes or no.
I want to know if inputed date of birth is over 18 or under.
def is_under_18(birth):
now = date.today()
return (
now.year - birth.year < 18
or now.year - birth.year == 18 and (
now.month < birth.month
or now.month == birth.month and now.day <= birth.day
)
)
And then:
year = int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))`
birth = date(year,month,day)
if is_under_18(birth):
print('Under 18')
else:
print('Adult')
However, the only thing is, say I add a user which his birthday is the 25th of November 2004. The program lets me add it because it does not count the month. If I add a user which was born the 1st of January 2005, it doesn't allow me because 2022-2005=17.
Your original code doesn't seem to have a problem with the dates you mention, but does have a bug as Nov 22, 2004 is "Under 18" and today's date is Nov 22, 2022 (18th birthday). Use now.day < birth.day instead.
But if you compute the birthday required to be 18 by replacing today's year with 18 less, then directly compare the dates, you don't have to have a complicated comparison:
from datetime import date
def is_under_18(birth):
# today = date.today()
today = date(2022,11,22) # for repeatability of results
born_on_or_before = today.replace(year=today.year - 18)
return birth > born_on_or_before
print(f'Today is {date.today()}')
for year,month,day in [(2004,11,21), (2004,11,22), (2004,11,23), (2004,11,25), (2005,1,1)]:
birth = date(year,month,day)
if is_under_18(birth):
print(f'{birth} Under 18')
else:
print(f'{birth} Adult')
Output:
Today is 2022-11-22
2004-11-21 Adult
2004-11-22 Adult
2004-11-23 Under 18
2004-11-25 Under 18
2005-01-01 Under 18
I have started leaning python programming.I am making the project given to me. when ever i give input it says invalid option. i am not able to solve the problem .i don't know were i am going wrong. i have tried every thing that i know. please help !
my output
python bikeshare.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
Invalid choice...
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
thank you for the help
import time
import pandas as pd
import numpy as np
CHICAGO = 'Chicago'
NYC = 'New York City'
WASHINGTON = 'Washington'
CITY_DATA = { CHICAGO: 'chicago.csv',
NYC: 'new_york_city.csv',
WASHINGTON: 'washington.csv' }
DAYS_OF_WEEK = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday']
MONTHS_OF_YEAR = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
HOURS = [
'12 AM'
'1 AM',
'2 AM',
'3 AM',
'4 AM',
'5 AM',
'6 AM',
'7 AM',
'8 AM',
'9 AM',
'10 AM',
'11 AM',
'12 PM',
'1 PM',
'2 PM',
'3 PM',
'4 PM',
'5 PM',
'6 PM',
'7 PM',
'8 PM',
'9 PM',
'10 PM',
'11 PM'
]
MINUTE_SEC = 60
HOUR_SEC = 60 * MINUTE_SEC
DAY_SEC = 24 * HOUR_SEC
WEEK_SEC = 7 * DAY_SEC
# print(CITY_DATA)
START_TIME = 'Start Time'
END_TIME = 'End Time'
BIRTH_YEAR = 'Birth Year'
START_STATION = 'Start Station'
END_STATION = 'End Station'
TRIP_DURATION = 'Trip Duration'
GENDER = 'Gender'
# Added columns
START_MONTH = 'Start Month'
START_DAY_OF_WEEK = 'Start Day of Week'
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(int) month - name of the month to filter by, or "all" to apply no month filter
(int) day - name of the day of week to filter by, or "all" to apply no day filter
"""
invalid_choice = "Invalid choice..."
ALL = 'all'
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
while True:
print("Please enter the number of which city you would like to explore: ")
print("1 Chicago, 2 New York City, 3 Washington")
location = input(">")
if location == '1':
city = CHICAGO
print("You chose Chicago")
break
elif location == '2':
city = NYC
print("You chose New York City")
break
elif location == '3':
city = WASHINGTON
print("You chose Washington")
break
else:
print(invalid_choice)
while True:
get_city = input('\nHello! Let\'s explore some US bikeshare data!\n'
'Would you like to see data for Chicago, New York, or Washington?\n')
if get_city.lower() in ('chicago', 'new york', 'washington'):
if get_city.lower() == 'chicago':
city_filename = chicago
elif get_city.lower() == 'new york':
city_filename = new_york_city
elif get_city.lower() == 'washington':
city_filename = washington
break
print('Enter a valid city name provided in the options')
while True:
print("Please enter the number of the (start) month you would like to explore or \"{}\": ".format(ALL))
print("1 January ... 6 June")
m = input(">")
if m == ALL:
month = None
break
try:
month = int(m)
except ValueError:
print(invalid_choice)
continue
else:
if month >= 1 and month<=6:
print("You chose " + MONTHS_OF_YEAR[month-1])
break
elif month <= 12:
print("Only January to June are in this dataset")
print(invalid_choice)
continue
else:
print(invalid_choice)
continue
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
print("Please enter the number of the (start) day of the week that you would like to explore or \"{}\": ".format(ALL))
print("1 Monday ... 7 Sunday")
d = input("> ")
if d == ALL:
day = None
break
try:
day = int(d)
except ValueError:
print(invalid_choice)
continue
else:
if day >= 1 and day<=7:
day -= 1
print("You chose " + DAYS_OF_WEEK[day])
break
else:
print(invalid_choice)
continue
print_divider()
return city, month, day
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, month is None, day is None)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
trip_length_time_of_day_correlation(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
print("Bye!")
break
if __name__ == "__main__":
main()
The code worked with me... How are you running it?
Your comparison is looking for the number as a string. If you use the standard input (eg, running in a terminal), then it will read it in as a string. But, if you pass in an integer somehow, then it won't match.
neil~$ python stack.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
You chose Chicago
Hello! Let's explore some US bikeshare data!
Would you like to see data for Chicago, New York, or Washington?
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
I am struggling to simplify the constraint for a few days now. still learning python. please help and thank you in advance.
Employees=['Paul', 'Ben', 'Nasim', 'Ceci', 'Victoria',]
Days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday']
avail = pulp.LpVariable.dicts("on_off", ((employee, day) for
employee in Employees for day in Days), cat="Binary")
requests={"Paul": {"Monday":1, "Tuesday":1, "Wednesday":1,
"Thursday":1, "Friday":1, "Saturday":1, "Sunday":1},
"Ben": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1,
"Friday":1, "Saturday":1, "Sunday":0},
"Nasim": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1,
"Friday":1, "Saturday":1, "Sunday":1},
"Ceci": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1,
"Friday":1,"Saturday":1, "Sunday":0},
"Victoria": {"Monday":1, "Tuesday":1, "Wednesday":0, "Thursday":0,
"Friday":0, "Saturday":0, "Sunday":0}}
for employee, day in avail:
prob += avail[employee, day] == [requests[i][j] for i in
requests for j in requests[i]]
as an example, the first few constraints:
"_C13: on_off_('Paul',_'Monday') = 28
_C14: on_off_('Paul',_'Tuesday') = 28
_C15: on_off_('Paul',_'Wednesday') = 28
_C16: on_off_('Paul',_'Thursday') = 28
_C17: on_off_('Paul',_'Friday') = 28
_C18: on_off_('Paul',_'Saturday') = 28"
("28" is just so happened to be the SUM of all the 1's and the 0's in my nested dict.)
Instead i like to have each variable matching 1's and 0's from my nested dict.
"_C13: on_off_('Paul',_'Monday') = 1
_C14: on_off_('Paul',_'Tuesday') = 1
_C15: on_off_('Paul',_'Wednesday') = 1
_C16: on_off_('Paul',_'Thursday') = 1
_C17: on_off_('Paul',_'Friday') = 1
_C18: on_off_('Paul',_'Saturday') = 1"
After the == sign you want the value 1 or 0 from the dictionary, therefore you should use:
for employee, day in avail:
prob += avail[employee, day] == requests[employee][day]
With requests[employee] you select the dictionary for that employee
requests['Paul'] = {"Monday":1, "Tuesday":1, "Wednesday":1,
"Thursday":1, "Friday":1, "Saturday":1, "Sunday":1}
Then by adding [day] you select the day from that dictionary:
requests['Paul']['Monday'] = 1