mad
mad

Reputation: 11

Splitting JSON array values to k/v and sequencing

So I managed to split the following JSON data to k/v pairs

"tags": [
    "category--Cola",
    "sugar--3.000000",
    "barcode--cola001",
    "barcode--cola001_1",
    "language--en",
    "sku--cola_classic",
    "sku--cola_cherry",
]

like so...

t = product['tags']
t_filtered = [k for k in t if '--' in k]
product['tags'] = dict(s.split('--') for s in t_filtered)

I want the output to be something like this:

{
"category": [Cola],
"sugar":[3.0],
"barcode":[cola001,cola001_1],
"language":[en],
"sku": [cola_classic, cola_cherry],

}

So I tried this... (ref: https://docs.python.org/3/library/collections.html#collections.defaultdict)

product['tags'] = dict(s.split('--') for s in t_filtered)
        s = product['tags']
        d = {}
        for k, v in s:
            d.setdefault(k, []).append(v)
        print(d)

But I'm getting this error:

ValueError: too many values to unpack (expected 2)

Also, just to verify s is a <classic 'dict'> so I can't figure out the issue.

Upvotes: 0

Views: 22

Answers (0)

Related Questions