I have a netCDF file containing monthly average temperatures around the globe dating back to 1948. For an assignment, I have to select any one provided datapoint, extract its mean temperature values for the months of December, January, February, and March, and then display it.
I've already unpacked the data and I have it collected in a list of dictionaries, as shown here:
For December:
decemberMeans = [
{'year': 1948, 'temp': 271.24}, {'year': 1949, 'temp': 271.28},
{'year': 1950, 'temp': 268.52}, {'year': 1951, 'temp': 269.63},
...,
{'year': 2015, 'temp': 277.23}, {'year': 2016, 'temp': 271.25}
]
Data corresponding to January, February, and March is structured in the same manner.
My next step is to plot it. I have to plot one line on the same graph for each set of data, and I'm using list comprehensions to do it. Right now my plotting code looks like this:
import matplotlib.pyplot as plt
plt.figure(1)
plt.hold(True)
plt.plot([data['years'] for data in decemberMeans], \
[data['temp'] for data in decemberMeans], 'k-')
plt.plot([data['years'] for data in januaryMeans], \
[data['temp'] for data in januaryMeans], 'r-')
plt.plot([data['years'] for data in februaryMeans], \
[data['temp'] for data in februaryMeans], 'b-')
plt.plot([data['years'] for data in marchMeans], \
[data['temp'] for data in marchMeans], 'y-')
plt.grid(True)
plt.show()
plt.close()
It plots just fine, but I can see that all of my list comprehensions are really redundant. Would there be a way that I could unpack the dictionary values in one fowl swoop so that I don't have to write data['...'] for data in list twice for each set?
P.S. - As I'm writing this I've started to realize that I could write a function to do the plotting (which would probably take even less time than writing out this post), but I'm still curious to know. Thanks to all in advance!