Question: I have a list of products with their name and time. I want to create a list that retrieved the most recent date for the kind of product. My initial plan is to create a sublist for each kind of product and the get the most recent of that sublist. I want to know if there is more efficient way of doing it since there could be more on the list.

```
products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
            {'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
            {'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
            {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]

Veggies = [x for x in products if x['name'] == 'Veggie']
...
new_products.append(get_recent(Veggies))

```

Desired output:

```
new_products = [{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
            {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]

```

Thanks in advance!

Answer: 
Here is an option using `collections.defaultdict`:

```py
from collections import defaultdict
from pprint import pprint

products = [
    {'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
    {'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
    {'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
    {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}
]

d = defaultdict(list)

for product in products:
    d[product['name']].append(product['time'])

new_products = [{'name': item, 'time': max(times)} for item, times in d.items()]

```

And the result will be:

```py
pprint(new_products)
[{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
 {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]

```
You can order a list of dictionary by any key you want.
In this example, products(or Veggies ) is passed to the built-in ​sorted() function, which accepts a keyword argument key. Itemgetter creates a callable that accepts a single item from the product(or Veggies) array and as input and returns a value that will be used as the basis for sorting it.

```py
from operator import itemgetter

products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
            {'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
            {'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
            {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]

rows_by_date = sorted(products, key=itemgetter('time'))
print(rows_by_date)

```

OUTPUT

```
[{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'}, 
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'}, 
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'}, 
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]

```