I've got a list of dictionaries that is already sorted by a key id
.
y = [{'id': 0, 'name': 'Frank'},
{'id': 5, 'name': 'Hank'},
{'id': 8, 'name': 'Fred'},
{'id': 30, 'name': 'Jill'}]
I want to insert a new element into the list.
y.append({'id': 6, 'name': 'Jenkins'})
How do I avoid sorting the list again as follows once the new element is added?
y = sorted(y, key=lambda x: x['id'])
The ideal outcome is:
y = [{'id': 0, 'name': 'Frank'},
{'id': 5, 'name': 'Hank'},
{'id': 6, 'name': 'Jenkins'},
{'id': 8, 'name': 'Fred'},
{'id': 30, 'name': 'Jill'}]
Edit:
Using bisect.insort(y, {'id': 6, 'name': 'Jenkins'})
will work only for the first key, if the dict is sorted by name, it will fail.