Adjusting nested dictionary depending on provided key values
<p>I would like to create the following dictionary based on various parameters given by <code>params</code>. Now I do not want to add keys which provide no value. So for instance if <code>params['ean']</code> is blank or does not exist I want to exclude the entire line <code>"EAN": params['ean']</code>. Any suggestions are highly welcome.</p>

<pre><code>myitem = {
"Item": {
     "Title": params['title'],
     "Description": "Some Text",
     "PrimaryCategory": {"CategoryID": params['category_id']},
     "ISBN": params['isbn'],
     "EAN": params['ean']
}
}
</code></pre>

<p>Please note that that params will not have the same keys like myitem.</p>

<p>I don't think i understand the question perfectly but how about something like that:</p>

<pre><code>myitem = {}
myitem['Item'] = {"Description": "Some Text"}
for keys in ['title', 'category_id', 'isbn', 'ean']:
    if params[keys]:
        myitem['Item'].append({keys.upper(): params[keys]})
</code></pre>

<p>which produces:</p>

<pre><code>myitem = {"Item": {"TITLE": params['title'],
                   "Description": "Some Text",
                   "CATEGORY_ID": params['category_id'],
                   "ISBN": params['isbn'],
                   "EAN": params['ean']
                   }
          }
</code></pre>

<p>Notice that at this stage the category id does not match your specifications exactly but that can be easily <em>fetched</em> using the following:</p>

<pre><code>myitem["item"].append({"PrimaryCategory": myitem["item"].pop(["CategoryID"])})
</code></pre>

<p>which takes advantage of the <code>pop</code>'s return so it removes and re-adds the <code>"CATEGORY_ID": params['category_id']</code> key value pair leaving you with the desired result (hopefully).</p>

python dictionary conditional