compguy24
compguy24

Reputation: 957

Create a list, replace null values with values from a different list at the same index

I query an api:

url = 'https://api.forecast.io/forecast/'+api_key+'/'+lat+','+lng
f = urllib2.urlopen(url)
json_string = f.read()
parsed_json = json.loads(json_string)
c = parsed_json['currently']

Some keys are defined, and others are not:

if 'temperature' in c: 

I want to build an object of a few specific values:

vector = [c['temperature'], ... c['wind_speed']

In total, there should be 11 items. If a key is undefined, I want to replace the value in that position from another list with same indeces.

averages = [average_temp, ... average_wind]

Something like this:

# for each of the keys I want:
   # if it is defined:
      # add this value to the list
   # else:
      # add the value at the same index in the averages vector

I imagine you might index through both vectors at the same time. Of course, the first vector has not been defined yet. Somehow the values need to be indexed first. What is the pythonic way of doing this?

Upvotes: 1

Views: 460

Answers (1)

abarnert
abarnert

Reputation: 365717

Whenever your problem includes "… from a different list at the same index", this is a case for zip. zip takes a pair of lists, and turns it into a list of pairs.

Then, you need an expression that's the left thing unless it's null, in which case the right thing.

And then you use a comprehension to map that over the whole zip.

So:

[a if a != null else b for a, b in zip(A, B)]

(I don't know what your "null" means or how you check it, but just replace the a != null with a is not None or not a.is_null() or whatever's appropriate.)

Upvotes: 3

Related Questions