Transform dictionary object
<p>This dict structure :</p>

<pre class="lang-py prettyprint-override"><code>data = {
    'a': { 'category': ['c', 'd'] },
    'b': { 'category': ['c', 'd'] }
}
</code></pre>

<p>should become this dict structure:</p>

<pre class="lang-py prettyprint-override"><code>data = {
    'c' : ['a', 'b'],
    'd' : ['a', 'b']
}
</code></pre>

<p>I have following approach:</p>

<pre class="lang-py prettyprint-override"><code>for key, value in data.items():
    if isinstance(value, dict):
        if 'category' in value:
            for cat in value['category']:
                if cat in categories:
                    categories[cat].append(key)
                else:
                    categories[cat] = [key]
</code></pre>

<p>I want to know if there is any way to simplify my approach. I am using python 3.5</p>

<pre><code>if 'category' in value:
</code></pre>

<p>This line makes sure that the key <code>category</code> is in the dictionary, before using it. Then you get the value from the dictionary corresponding to <code>category</code> and iterate it. You can simplify this with <code>dict.get</code> method, which would return a default value, if the key is not there in the dictionary. So you can do something like this</p>

<pre><code>for cat in value.get('category', []):
</code></pre>

<p>If the <code>category</code> doesn't exist in the dictionary, then an empty list is returned and the loop will have nothing to iterate.</p>

<hr>

<p>Similarly, you are checking if the key exists in the <code>categories</code> dictionary, if not, setting a default value (which is a list). You can avoid that <code>if...else</code> also, with <code>dict.setdefault</code>, like this</p>

<pre><code>categories = {}
for key, value in data.items():
    if isinstance(value, dict):
        for cat in value.get('category', []):
            categories.setdefault(cat, []).append(key)
</code></pre>

<p><code>dict.setdefault</code> is similar to <code>dict.get</code>, except that it sets the default value against the key and returns the value corresponding to the key.</p>

python python-3.x dictionary