4 ms·
> Unpacking doesn't let you specify default values if cardinality doesn't match, nor can you extract dictionaries by keys. I'm a bit confused by this one, but
by z3c0 4y ago
> Unpacking doesn't let you specify default values if cardinality doesn't match, nor can you extract dictionaries by keys.
I'm a bit confused by this one, but maybe I'm misunderstanding. Does this not accomplish what you're defining?
def parse_record(first=0, second=1, **all_the_others) -> dict:
return dict(first=first, second=second, **all_the_others)
dictionary = dict(first=99, third=2)
parse_record(**dictionary)
> {"first": 99, "second": 1, "third": 2}
- bjourne 4y agoThat's packing. Unpacking would be something like this: d = {'a' : 10, 'b' : 20, 'c' : 30} {'a' : v1, 'b' : v2, **others} = d print(v1, v2, others) # prints 10, 20, {'c' : 30}
- BiteCode_dev 4y agoExactly. The working code in Python, as a function, would be: def extract(mapping, *args, **kwargs): for a in args: yield mapping[a] for key, default in kwargs.items(): yield mapping.get(key, default)