如何将第一行数组中的值与第一列中的值匹配以创建json?

时间:2014-10-20 03:02:29

标签: python json

我在python中有一个包含以下数据的列表列表:

Metric, Person1, Person2, Person3, Person4, ...
Sex|Male, 0.50,  0.75,    0.35,     0.80, ...
Sex|Female, 0,50, 0.25,   0.65,     0.20, ....
Age| 18-24, 0.25,  0.20,   0.15,     0.17, ...

我想创建一个具有以下结构的JSON:

 data = [{Person1:[{Sex|Male:0.50},  {Sex|Female:0.50}, {Age|18-24:0.25}]}, {Person2:[{Sex|Male:0.75},{Sex|Female:0.25}, {Age|18-24:0.20}]}, ...]

如何使用Python匹配这些值?

2 个答案:

答案 0 :(得分:0)

如你所说,如果你有一份清单清单,即

data = [
    ['Metric', 'Person1', 'Person2', 'Person3', 'Person4'],
    ['Sex|Male', 0.5, 0.75, 0.35, 0.8],
    ['Sex|Female', 0, 50, 0.25, 0.65, 0.2],
    ['Age| 18-24', 0.25, 0.2, 0.15, 0.17],
]

以下将产生所需的输出:

>>> l = zip(*data)    # swap rows and columns - it's easier to work this way
>>> from pprint import pprint
>>> pprint(l)
[('Metric', 'Sex|Male', 'Sex|Female', 'Age| 18-24'),
 ('Person1', 0.5, 0, 0.25),
 ('Person2', 0.75, 50, 0.2),
 ('Person3', 0.35, 0.25, 0.15),
 ('Person4', 0.8, 0.65, 0.17)]

>>> result = []
>>> for row in l[1:]:
...     result.append({row[0] : [{l[0][i] : row[i]} for i in range(1, len(row))]})

>>> pprint(result)
[{'Person1': [{'Sex|Male': 0.5}, {'Sex|Female': 0}, {'Age| 18-24': 0.25}]},
 {'Person2': [{'Sex|Male': 0.75}, {'Sex|Female': 50}, {'Age| 18-24': 0.2}]},
 {'Person3': [{'Sex|Male': 0.35}, {'Sex|Female': 0.25}, {'Age| 18-24': 0.15}]},
 {'Person4': [{'Sex|Male': 0.8}, {'Sex|Female': 0.65}, {'Age| 18-24': 0.17}]}]

答案 1 :(得分:0)

你有一个Python列表,对吧?

让列表为数据,列数为Nc,行数为Nr。

列表理解方式:

dict = {data[i][0]:[{data[j][0]:data[j][i]} for j in range(1,Nr)] for i in range(1,Nc)}

或正常循环:

for i in range(1,Nc):
  dict[data[i][0]] = []
  for j in range(1,Nr):
    dict.append({data[j][0]:data[j][i]})

测试:

>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> dd = {l[0][i]:[{l[j][0]:l[j][i]} for j in range(1,3)] for i in range(1,3)}
>>> dd
{2: [{4: 5}, {7: 8}], 3: [{4: 6}, {7: 9}]}