Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your data structure is strange for this operation; here is a different approach:</p> <pre><code>d = {} for i in dates: if not i['basic'] in d: d[i['basic']] = {} d[i['basic']]['start_date'] = [] d[i['basic']]['end_date'] = [] d[i['basic']]['start_date'].append(int(i['start_date'].replace('-',''))) d[i['basic']]['end_date'].append(int(i['end_date'].replace('-',''))) # This will give you: &gt;&gt;&gt; d {1000.0: {'start_date': [20110101, 20110501], 'end_date': [20110131, 20110531]}, 2000.0: {'start_date': [20120101, 20120501], 'end_date': [20120131, 20120531]}, 3500.0: {'start_date': [20130101, 20130201], 'end_date': [20130131, 20130228]}, 2500.0: {'start_date': [20120701, 20120801], 'end_date': [20120731, 20120831]}, 4000.0: {'start_date': [20131101], 'end_date': [20131130]}} # Next, sort the start and end dates. We want the earliest start date, # and the last end date for each number for i in d.values(): i['start_date'].sort() i['end_date'].sort(reverse=True) # Now we have: &gt;&gt;&gt; d {1000.0: {'start_date': [20110101, 20110501], 'end_date': [20110531, 20110131]}, 2000.0: {'start_date': [20120101, 20120501], 'end_date': [20120531, 20120131]}, 3500.0: {'start_date': [20130101, 20130201], 'end_date': [20130228, 20130131]}, 2500.0: {'start_date': [20120701, 20120801], 'end_date': [20120831, 20120731]}, 4000.0: {'start_date': [20131101], 'end_date': [20131130]}} # To build our final result; we need to have for each # number, the earliest start date, and the latest end date (which are the first # items of each `start_date` and `end_date` dictionary keys # Then we just do some formatting to get it back in to the date string result = [] for i,v in d.iteritems(): j = {} j['basic'] = i # Convert the start and end dates into strings # and format them start = str(v['start_date'][0]) end = str(v['end_date'][0]) j['start_date'] = '{0}-{1}-{2}'.format(start[:4],start[4:6],start[-2:]) j['end_date'] = '{0}-{1}-{2}'.format(end[:4],end[4:6],end[-2:]) result.append(j) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload