Although it has been adopted, it can still be mentioned: When I see this setdefault, I think of collections.defaultdict, which is more powerful than setdefault. The accepted parameters can be the default initialization type or a function. In fact, it can be more concise
from collections import defaultdict
ips = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
result = defaultdict(list)
for v, k in ips:
result[k].append((v, k))
The above is the array, and the below is the JSON after the dict() serial number. Just traverse the array and concatenate it into a dictionary and output JSON.
import json
a = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
b = dict()
for value in a :
number = value[0]
address = value[1]
if address not in b :
b[address] = []
b[address].append([number, address])
print json.dumps(b)
Improved based on the suggestions provided by @dokelung and @松林 two guys
Although it has been adopted, it can still be mentioned:
When I see this setdefault, I think of collections.defaultdict, which is more powerful than setdefault. The accepted parameters can be the default initialization type or a function. In fact, it can be more concise
The above is the array, and the below is the JSON after the dict() serial number. Just traverse the array and concatenate it into a dictionary and output JSON.