Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of all keys from a list of dictionaries

Say I have a list of dictionaries. They mostly have the same keys in each row, but a few don't match and have extra key/value pairs. Is there a fast way to get a set of all the keys in all the rows?

Right now I'm using this loop:

def get_all_keys(dictlist):
    keys = set()
    for row in dictlist:
        keys = keys.union(row.keys())

It just seems terribly inefficient to do this on a list with hundreds of thousands of rows, but I'm not sure how to do it better

Thanks!

like image 710
Joe Pinsonault Avatar asked Nov 20 '25 18:11

Joe Pinsonault


1 Answers

You could try:

def all_keys(dictlist):
    return set().union(*dictlist)

Avoids imports, and will make the most of the underlying implementation of set. Will also work with anything iterable.

like image 142
Jon Clements Avatar answered Nov 22 '25 08:11

Jon Clements



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!