8👍
✅
You can use intersection operations (which sounds like what you really want, not union) to efficiently limit iteration to keys common to both dict
s, 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).
3👍
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
}
- Refresh <div> element generated by a django template
- Django-compressor not setting absolute CSS image paths on Heroku
- Django send_mail not working – No email delivered
- How to create a Django superuser if it doesn't exist non-interactively?
Source:stackexchange.com