python - How can I match values from first row of array with values from first column to create a json? -
python - How can I match values from first row of array with values from first column to create a json? -
i have list of lists in python has info this:
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, ...
i create json next structure:
info = [{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}]}, ...]
how can match these values using python?
if, say, have list of lists, i.e.
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], ]
the next produce required output:
>>> l = zip(*data) # swap rows , columns - it's easier work way >>> 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 = [] >>> row in l[1:]: ... result.append({row[0] : [{l[0][i] : row[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}]}]
python json
Comments
Post a Comment