I was doing django project about processing request.data
and from.cleaned_data
issues. When user only inputs specify fields, it will send request to my server. Next, the form class process the request, except processing inputed fields and return no inputted fields from form built-in fields.
This is request data:
<QueryDict: {u'is_public': [u'True']}>
This is cleaned data from from class:
{'name': u'', 'devie_type': u'', 'is_public': True, 'serial_num': u'', 'is_online': False, 'operation_system': u''}
I know these are dictionary type. I hope getting their union keys of them and values of cleaned data. I expect that it returns:
{u'is_public': True}
This is my attempt:
a = {}
for k in request.data:
if k in the_form.cleaned_data:
a[k] = the_form.cleaned_data[k]
print a
Is it readable? or is there any built-in functions about processing union dictionary in python?
In this tutorial, we will look at how to get the keys of a Python dictionary with the help of some examples. How to get the keys of a dictionary in Python? You can use the Python dictionary keys () function to get all the keys in a Python dictionary. The following is the syntax: It returns a dict_keys object containing the keys of the dictionary.
The keys here are the employee names whereas the values are their respective departments. Let’s get all the keys in the dictionary using the dictionary’s keys () function. You can see that we get all the names of the employees (the keys in the dictionary employee) in a dict_keys object.
Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary. Note: The order of these key values in the list may not always be the same. Here, when the dictionary is updated, keys are also automatically updated to show the changes.
We all have those moments when we want to merge two Python dictionaries together based on their keys. The traditional way to do this was to use the dict.update () method.
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).
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