Reputation: 365
I have the following code which gives the city based on IP:
RANGES = {
'Paris': [
{'start': '10.10.0.0', 'end': '10.10.255.255'},
{'start': '192.168.1.0', 'end': '192.168.1.255'},
],
'NYC': [
{'start': '10.12.0.0', 'end': '10.12.255.255'},
{'start': '172.16.10.0', 'end': '172.16.11.255'},
{'start': '192.168.2.0', 'end': '192.168.2.255'},
]
}
def get_city(self, ip):
print 'Here'
for city, ipranges in self.RANGES.items():
for iprange in ipranges:
if ip >= iprange['start'] and ip <= iprange['end']:
return city
I have another variable:
RECORDS = [
{'user_id': 1, 'created_at': '2017-01-01T10:00:00', 'status': 'paying'},
{'user_id': 1, 'created_at': '2017-03-01T19:00:00', 'status': 'paying'},
{'user_id': 1, 'created_at': '2017-02-01T12:00:00', 'status': 'cancelled'},
{'user_id': 3, 'created_at': '2017-10-01T10:00:00', 'status': 'paying'},
{'user_id': 3, 'created_at': '2016-02-01T05:00:00', 'status': 'cancelled'},
]
For which I'm trying to implement this function:
def get_status(self, user_id, date): //should return the status
I'm not sure how to parse the list -> match the values -> return the status for the matching combination of created_at
and user_id
Upvotes: 0
Views: 82
Reputation: 6781
This should do it :
def get_status(user_id, date):
for i,ele in enumerate(RECORDS):
if ele['user_id']==user_id and ele['created_at']==date:
return ele['status']
print(get_status(1, '2017-02-01T12:00:00'))
#'cancelled'
Here, we are going through the list
and using the dict
element in it to match its keys (user_id
and created_at
) and check if the values match with the required values. Ofcourse, make sure that the RECORDS
value should be available in the function.
Upvotes: 1
Reputation: 574
You can simply do this
>>> def get_status(user_id, date):
for rec in RECORDS:
if rec['user_id'] == user_id and rec['created_at'] == date:
return rec['status']
>>> get_status(1, '2017-01-01T10:00:00')
'paying'
>>>
Upvotes: 1