Is there a way to get a dict comprehension to raise an exception if it would override a key?
For example, I would like the following to error because there are two values for the key 'a'
:
>>> {k:v for k, v in ('a1', 'a2', 'b3')}
{'a': '2', 'b': '3'}
I realise this can be done with a for
loop. Is there a way to do it while keeping the comprehension syntax?
When duplicate keys are encountered during the assignment, the value will be the last assigned one. Keys must be immutable. This means you can use strings, numbers, or tuples as dictionary keys, but something like ['key'] is not allowed.
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.
You can use a generator with a helper function:
class DuplicateKeyError(ValueError): pass
def dict_no_dupl(it):
d = {}
for k, v in it:
if k in d: raise DuplicateKeyError(k)
d[k] = v
return d
dict_no_dupl((k, v) for k, v in ('a1', 'a2', 'b3'))
This does add a helper function, but keeps the comprehension syntax (reasonably) intact.
If you don't care about which key caused a collision:
Check that the generated dict has the appropriate size with len()
.
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