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!
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.
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