Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise error if a Python dict comprehension overwrites a key

Tags:

python

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?

like image 427
Gary van der Merwe Avatar asked May 14 '15 13:05

Gary van der Merwe


People also ask

What happens when duplicate keys encountered during assignment in dictionary?

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.

Can we update key-value in dictionary in Python?

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.

Is dictionary comprehension faster than for loop?

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.

What is dict comprehension in Python?

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.


2 Answers

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.

like image 100
orlp Avatar answered Oct 16 '22 13:10

orlp


If you don't care about which key caused a collision:

Check that the generated dict has the appropriate size with len().

like image 14
Karoly Horvath Avatar answered Oct 16 '22 13:10

Karoly Horvath