Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - append to list of dicts while keeping order

Tags:

python

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!

like image 274
i_trope Avatar asked Mar 21 '26 07:03

i_trope


2 Answers

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.

like image 127
MikeTwo Avatar answered Mar 23 '26 21:03

MikeTwo


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')]
like image 42
Roland Smith Avatar answered Mar 23 '26 23:03

Roland Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!