python 中如何格式化数据
天蓬老师
天蓬老师 2017-04-17 17:53:37
0
3
587
(
    (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')]
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
小葫芦

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
洪涛

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))
Peter_Zhu

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template