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 think the following code does what you are looking for.</p>

<pre><code>d = {}

def addItem(name, description, params):
    d[name] = {}
    if 'title' in params:
        d[name]['Title'] = params['title']
    if 'category_id' in params:
        d[name]['PrimaryCategory'] = {"CategoryID" : params['category_id']}
    if 'isbn' in params:
        d[name]['ISBN'] = params['isbn']
    if 'ean' in params:
        d[name]['EAN'] = params['ean']
    d[name]['Description'] = description

params1 = {'title' : 'Boh'}
addItem('item1', 'item1 description', params1)
params2 = {'title' : 'Boh 2', 'isbn' : '12345'}
addItem('item2', 'item2 description', params2)
print d
</code></pre>

python dictionary conditional