JDev
JDev

Reputation: 1822

Python: How to convert json comma separated key to a dictionary

I have a JSON in below format:

{
  '166, 175': 't2',
  '479': 't3'
}

I want to convert this to a map:

166: 't2'
175: 't2'
479: 't3' 

Upvotes: 1

Views: 168

Answers (3)

Nagesh Dhope
Nagesh Dhope

Reputation: 837

Bit complicated though

src = {
      '166, 175': 't2',
      '479': 't3'
    }

output = dict(reduce(lambda a, b: a + b, map(lambda b:zip(b.split(', '), [a[b]] * len(b.split(', '))), src)))

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

You can use some dictionary comprehension here:

{
    int(k): v
    for ks, v in data.items()
    for k in ks.split(',')
}

For the sample data, this gives us:

>>> {
...     int(k): v
...     for ks, v in data.items()
...     for k in ks.split(',')
... }
{166: 't2', 175: 't2', 479: 't3'}

Upvotes: 3

ilmiacs
ilmiacs

Reputation: 2576

src = {
  '166, 175': 't2',
  '479': 't3'
}
res = {}
for k, v in src.items():
    for i in k.split(', '):
        res[int(i)] = v
print(res)

Upvotes: 3

Related Questions