Home > Back-end >  Unpacking a list of dictionaries to get all their keys
Unpacking a list of dictionaries to get all their keys

Time:10-08

I am writing a script to add missing keys within a list of dictionaries and assign them a default value. I start by building a set of all the possible keys that appear in one or more dictionaries.

I adapted a nice snippet of code for this but I'm having trouble fully wrapping my head around how it works:

all_keys = set().union(*dicts)

From how I understand this, my list of dictionaries dicts is unpacked into individual (dictionary) arguments for the union method, which merges them all together with the empty set, giving me a set of keys.

What isn't clear to me is why this code builds the set using just the keys of the dictionaries, while discarding their associated values. This is in fact what I want to happen, but how it is achieved here is murky. For example, I know unpacking a dictionary with a single * unpacks just the keys, which seems like what is happening here, except in my code I am not explicitly unpacking the contents of the dictionaries, only the list that contains them.

Can someone explain to me a little more explicitly what is happening under the hood here?

CodePudding user response:

If you wrote:

s1 = set()
s2 = s1.union(iterable1, iterable2, iterable3)

the union() method would unpack each iterableX to get the values to combine with s1.

Your code is simply getting all the iterables by spreading dicts, so it's equivalent to

s2 = s1.union(dicts[0], dicts[1], dicts[2], ...)

and it unpacks each dictionary, getting their keys.

  • Related