mk8efz mk8efz - 1 month ago 8
Python Question

Remove Older Tuples from List

I have a list of paths and dates:

myList = [('Y:\\Resources\\Project 1', '2016-07'),
('Y:\\Resources\\Project 1', '2016-08'),
('Y:\\Resources\\Project 2', '2014-01'),
('Y:\\Resources\\Project 3', '2015-12'),
('Y:\\Resources\\Project 3', '2016-02'),
('Y:\\Resources\\Project 3', '2013-08'),
('Y:\\Resources\\Project 4', '2016-04')]


I would like to remove the items with older dates and return:

newList = [('Y:\\Resources\\Project 1', '2016-08'),
('Y:\\Resources\\Project 2', '2014-01'),
('Y:\\Resources\\Project 3', '2016-02'),
('Y:\\Resources\\Project 4', '2016-04')]

Answer

You may use dict to create the unique entities as:

>>> my_dict = {}
>>> for key, value in myList:
...     if key in my_dict:
...         if my_dict[key] < value:
...             my_dict[key] = value
...     else:
...         my_dict[key] = value
...

where myList is holding the value as is mentioned in question. In order to convert dict to list of tuples, do dict.items() as:

>>> new_list = my_dict.items()
>>> new_list
[('Y:\\Resources\\Project 4', '2016-04'), 
 ('Y:\\Resources\\Project 3', '2016-02'), 
 ('Y:\\Resources\\Project 2', '2014-01'), 
 ('Y:\\Resources\\Project 1', '2016-08')] 

Note: dict do not maintain the order of elements. In case you want to maintain the order, use collections.OrderedDict()

Comments