I have this data for a project with a friend:
arr = [{'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'Thirdkey 1', 'Value':100},
{'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':130},
{'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 1', 'Value':230},
{'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':300},
{'Key':'Key 2', 'SecondKey':'SecondKey 4', 'ThirdKey':'ThirdKey 1', 'Value':111},
{'Key':'Key 2', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':400},
{'Key':'Key 2', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':230}
]
I tried functions like this:
def array_to_dict(arr, classification):
dct = tree()
for d in arr:
dct[d["Key"]]=(d)
pprint.pprint(dct)
def tree():
return defaultdict(tree)
def array_to_dict_recursive(arr, classification):
result = defaultdict(arr)
for v, k in arr:
result[k].append(v)
final_result = [{'type': k, 'items': v} for k, v in result.items()]
print (str(final_result))
def array_cool(arr):
#pprint.pprint(arr)
arr.sort(key=operator.itemgetter('Key'))
pprint.pprint(arr)
list1= []
print("")
for key, items in itertools.groupby(arr, operator.itemgetter('Key')):
list1.append(list(items))
pprint.pprint(list1)
And I want it to appear like a JSON file in this way:
{
"Key 1": {
"SecondKey 2": {
"ThirdKey 2": [
{
"Key": "Key 1",
"Value": 300,
"SecondKey": "SecondKey 2",
"ThirdKey": "ThirdKey 2"
}
],
"ThirdKey 1": [
{
"Key": "Key 1",
"Value": 230,
"SecondKey": "SecondKey 2",
"ThirdKey": "ThirdKey 1"
}
]
},
"SecondKey 1": {
"ThirdKey 2": [
{
"Key": "Key 1",
"Value": 130,
"SecondKey": "SecondKey 1",
"ThirdKey": "ThirdKey 2"
}
],
"ThirdKey 1": [
{
"Key": "Key 1",
"Value": 100,
"SecondKey": "SecondKey 1",
"ThirdKey": "ThirdKey 1"
}
]
}
},
"Key 2": {
"SecondKey 4": {
"ThirdKey 1": [
{
"Key": "Key 2",
"Value": 111,
"SecondKey": "SecondKey 4",
"ThirdKey": "ThirdKey 1"
}
]
},
"SecondKey 2": {
"ThirdKey 2": [
{
"Key": "Key 2",
"Value": 400,
"SecondKey": "SecondKey 2",
"ThirdKey": "ThirdKey 2"
}
]
},
"SecondKey 1": {
"ThirdKey 2": [
{
"Key": "Key 2",
"Value": 230,
"SecondKey": "SecondKey 1",
"ThirdKey": "ThirdKey 2"
}
]
}
}
}
I tried sorting, but sorting puts the Key in the second position and mess with the next sorting process, and it's not working.
json.dumpit?