'Print a paragraph using some of the dictionary values
The code below is my program. I want to print the outcome more user-friendly like, "Here is your forecast for New York. Expect cloudy conditions with temperatures topping out at 24 degrees. Winds will be……". I tried several methods but seemed to fail by each one. The best I got was printing it as a list. Any suggestions? Thank you in advance!
#declare cities and their weather for the program
city_1 = {'city name':'New York', 'city_zip':'10001', 'forecast_temp':24, 'forecast_condition':'cloudy', 'forecast_wind_direction':'north', 'forecast_wind_speed':13, 'forecast_precip':'sleet'}
city_2 = {'city_name' : 'Chicago', 'city_zip' : '60007', 'forecast_temp' : 45, 'forecast_condition' : 'fog', 'forecast_wind_direction': 'east', 'forecast_wind_speed': 10, 'forecast_precip': 'rain' }
city_3 = {'city_name' : 'Miami', 'city_zip' : '33101', 'forecast_temp' : 77, 'forecast_condition' : 'sunny', 'forecast_wind_direction': 'south', 'forecast_wind_speed': 12, 'forecast_precip': 'none' }
def userLocation(): #get city from user
"""Get location from user."""
location = ""
while location != ("") or location != ("q"):#program does not have valid city yet
location = input("Enter the zip code or city that you want to get the weather for: \nEnter 'q' to quit.\n")
if location.lower() == "new york" or location == "10001":
city = city_1
break
elif location.lower() == "chicago" or location == "60007":
city = city_2
break
elif location.lower == "miami" or location == "33101":
city = city_3
break
elif location.lower() == "q":#user wants to quit program
exit()
return city
def printInfo(city): #print weather information to user for specified city
"""Print weather information about specific city."""
print ('\n'.join("{}: {}".format(k, v) for k, v in city.items()))
print ("Hello, I will be giving you the weather for any zip code or city that you want!")
city = userLocation()
printInfo (city)
Solution 1:[1]
If the keys in the dictionary are always the same, you could try a formatted string:
print(f'Here is your forecast for {city["city_name"]}. Expect {city["forecast_condition"]} conditions with temperatures topping out at {city["forecast_temp"]} degrees.')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leeuwtje |
