(
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
如何格式化为以下格式 用python
{
'10.121.1.1:4730':
[(1, '10.121.1.1:4730')],
'127.0.0.1:4730':
[(2, '127.0.0.1:4730'), (3, '127.0.0.1:4730')]
}
高洛峰2017-04-17 17:55:37
Improved based on the suggestions provided by @dokelung and @松林 two guys
ips = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
dic = {}
for v, k in ips:
dic.setdefault(k, []).append((v, k))
print dic
PHP中文网2017-04-17 17:55:37
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))
天蓬老师2017-04-17 17:55:37
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)