How to convert all lists to sets when json file is loaded
<p>I have json files that look like this:</p>

<pre><code>{
    "K1": {
        "p": [
            "A"
        ], 
        "s": [
            "B", 
            "C"
        ]
    }, 
    "K2": {
        "p": [
            "A", 
            "F"
        ], 
        "s": [
            "G", 
            "H",
            "J"
        ]
    }
}
</code></pre>

<p>I can easily read in this data:</p>

<pre><code>import json

with open('json_lists_to_sets.json') as fi:
    data = json.load(fi)
</code></pre>

<p>Then <code>data</code> looks as follows:</p>

<pre><code>{u'K2': {u'p': [u'A', u'F'], u's': [u'G', u'H', u'J']}, u'K1': {u'p': [u'A'], u's': [u'B', u'C']}}
</code></pre>

<p>For my further analysis, however, it would be better to use <code>sets</code> instead of <code>lists</code>. I can of course convert <code>lists</code> to <code>sets</code> after I have read in the data:</p>

<pre><code>for vi in data.values():
    vi['p'] = set(vi['p'])
    vi['s'] = set(vi['s'])
</code></pre>

<p>which gives me the desired output:</p>

<pre><code>print data['K2']
</code></pre>

<p>yields</p>

<pre><code>{u'p': {u'A', u'F'}, u's': {u'G', u'H', u'J'}}
</code></pre>

<p>My questions is whether I can convert these <code>lists</code> to <code>sets</code> directly when I read in the data in the <code>json.load</code> command, so something like "convert all lists you find to sets". Does something like this exist?</p>

<p>Below is the one liner expression to achieve this using <code>dict comprehension</code>:</p>

<pre><code>&gt;&gt;&gt; {key: {k: set(v) for k, v in nested_dict.items()} for key, nested_dict in data.items()}
{'K2': {'s': {'H', 'G', 'J'}, 'p': {'A', 'F'}}, 'K1': {'s': {'B', 'C'}, 'p': {'A'}}}
</code></pre>

<p>However, in case you want achieve it using <code>loop</code>, below is the example:</p>

<pre><code>data = {u'K2': {u'p': [u'A', u'F'], u's': [u'G', u'H', u'J']}, u'K1': {u'p': [u'A'], u's': [u'B', u'C']}}
for key, nested_dict in data.items():
    data[key] = {k: set(v) for k, v in nested_dict.items()}

# Value of 'data': {'K2': {'s': {'H', 'G', 'J'}, 'p': {'A', 'F'}}, 'K1': {'s': {'B', 'C'}, 'p': {'A'}}}
</code></pre>

python json