I have a python list that contains dicts of personal information like so:
entries = [
{
"first_name": "philip",
"last_name": "fry"
},
{
"first_name": "john",
"last_name": "zoidberg"
}
]
I would like to add entries to this list, in such as way that ascending (last name, first name) order is maintained. The bisect module looks promising, but it does not seem to support this.
Any help is appreciated!
Depending on how performant you need it to be, you can just resort after each addition. Something like (untested code):
def add(item, aList):
aList.append(item)
return sorted(aList, key=lambda entry:"{}{}".format(entry['last_name'], entry['first_name'])
It's not efficient, but if you have the flexibility, it's simple.
If the list is homogeneous, i.e. all entries are a pair of names, you could use tuples instead of dicts since the keys don't add much value in this case.
And if you kept the tuples in last name, first name order you could use bisect:
In [1]: entries = [("fry", "philip"), ("zoidberg", "john")]
In [2]: entries.sort()
In [3]: entries
Out[3]: [('fry', 'philip'), ('zoidberg', 'john')]
In [4]: import bisect
In [5]: bisect.insort(entries, ("turanga", "leela"))
In [6]: entries
Out[6]: [('fry', 'philip'), ('turanga', 'leela'), ('zoidberg', 'john')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With