He’re an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings {'id': id, 'url': url}. Some ids in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:
def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d]
I suppose it’s quite efficient. But is there a ‘more Pythonic’ way ? Or perhaps a more efficient way ?
Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:
Although this came out as a one-liner, I still think it’s quite readable.
There are two things you have to keep in mind when using your original solution and mine:
If you don’t mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:
You might need to call it with
list(unique_mappings(mappings))if you need a list and not a generator.