Can someone explain why these two different code samples give different outputs? I'm confused on why the first sample appends "sunny" and "cloud" to all months, which is not what I want. I want the output of the second sample. However, I want to assign the variable "forecast", not its value to weatherReport["months"][month]. Is there a way to get the output of Sample 2 this way?
Sample 1:
weatherReport = {"months": {}}
forecast = []
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
for month in months[1:]:
weatherReport["months"][month] = forecast
weatherReport["months"]["June"].append("sunny")
weatherReport["months"]["December"].append("cloudy")
print weatherReport
Output for Sample 1:
{'months': {'February': ['sunny', 'cloudy'], 'October': ['sunny', 'cloudy'], 'March': ['sunny', 'cloudy'], 'August': ['sunny', 'cloudy'], 'May': ['sunny', 'cloudy'], 'December': ['sunny', 'cloudy'], 'June': ['sunny', 'cloudy'], 'September': ['sunny', 'cloudy'], 'April': ['sunny', 'cloudy'], 'July': ['sunny', 'cloudy'], 'November': ['sunny', 'cloudy']}}
Sample 2:
weatherReport = {"months": {}}
forecast = []
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
for month in months[1:]:
weatherReport["months"][month] = []
weatherReport["months"]["June"].append("sunny")
weatherReport["months"]["December"].append("cloudy")
print weatherReport
Output for Sample 2:
{'months': {'February': [], 'October': [], 'March': [], 'August': [], 'May': [], 'December': ['cloudy'], 'June': ['sunny'], 'September': [], 'April': [], 'July': [], 'November': []}}