I'm retrieving a list of (name
, id
) pairs and I need to make sure there's no duplicate of name
, regardless of the id
.
# Sample data
filesID = [{'name': 'file1', 'id': '353'}, {'name': 'file2', 'id': '154'},
{'name': 'file3', 'id': '1874'}, {'name': 'file1', 'id': '14'}]
I managed to get the desired output with nested loops:
uniqueFilesIDLoops = []
for pair in filesID:
found = False
for d in uniqueFilesIDLoops:
if d['name'] == pair['name']:
found = True
if not found:
uniqueFilesIDLoops.append(pair)
But I can't get it to work with list comprehension. Here's what I've tried so far:
uniqueFilesIDComprehension = []
uniqueFilesIDComprehension = [
pair for pair in filesID if pair['name'] not in [
d['name'] for d in uniqueFilesIDComprehension
]
]
Outputs:
# Original data
[{'name': 'file1', 'id': '353'}, {'name': 'file2', 'id': '154'},
{'name': 'file3', 'id': '1874'}, {'name': 'file1', 'id': '14'}]
# Data obtained with list comprehension
[{'name': 'file1', 'id': '353'}, {'name': 'file2', 'id': '154'},
{'name': 'file3', 'id': '1874'}, {'name': 'file1', 'id': '14'}]
# Data obtained with loops (and desired output)
[{'name': 'file1', 'id': '353'}, {'name': 'file2', 'id': '154'},
{'name': 'file3', 'id': '1874'}]
I was thinking that maybe the call to uniqueFilesIDComprehension
inside the list comprehension was not updated at each iteration, thus using []
and not finding corresponding values.