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>

<p>You can solve it with a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(list)</code></a>, iterating over the categories and appending keys:</p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt;
&gt;&gt;&gt; d = defaultdict(list)
&gt;&gt;&gt; for key, value in data.items():
...     for item in value['category']:
...         d[item].append(key)
... 
&gt;&gt;&gt; dict(d)
{'c': ['a', 'b'], 'd': ['a', 'b']}
</code></pre>

python python-3.x dictionary