[Fixed]-How do I get union keys of `a` and `b` dictionary and 'a' values?


You can use intersection operations (which sounds like what you really want, not union) to efficiently limit iteration to keys common to both dicts, then use a dict comprehension to achieve this fairly efficiently:

a = {k: the_form.cleaned_data[k]
     for k in request.data.viewkeys() & the_form.cleaned_data.viewkeys()}

So when a key exists in both the request and the cleaned data, you’ll have a mapping from that key to the cleaned data. All other keys that appear in only one input dict or the other are dropped. In Python 3, you’d replace .viewkeys() with just .keys() (and this won’t work before Python 2.7, which is where .viewkeys() was introduced).


There’s nothing inherently wrong with what you’re doing, all totally fine. However, the more pythonic way to do this would be to use a dictionary comprehension:

a = {
   k: the_form.cleaned_data[k]
   for k in request.data
   if k in the_form.cleaned_data


just do: request_data.update(form.cleaned_data)

Leave a comment