最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Spliting a JSON list obj into multiple based on values in python - Stack Overflow

programmeradmin0浏览0评论

I have JSON object something like below,

Data = [
    {
        'Name': 'A1',
        'Value': 10,
        'Type': 'AAA'
    },
    {
        'Name': 'A1',
        'Value': 20,
        'Type': 'AAA'
    },  
    {
        'Name': 'B1',
        'Value': 10,
        'Type': 'AAA'
    },
    {
        'Name': 'C1',
        'Value': 10,
        'Type': 'BBB'
    },
    {
        'Name': 'D1',
        'Value': 10,
        'Type': 'BBB'
    }
]

And i would like to split the object into a list based on "Type" and then based on the "Name" also to something like below,

Data = {
    'AAA': {
        'A1': [
            {
                'Name': 'A1',
                'Value': 10,
                'Type': 'AAA'
            },
            {
                'Name': 'A1',
                'Value': 20,
                'Type': 'AAA'
            },          
        ],
        'B1': [
            {
                'Name': 'B1',
                'Value': 10,
                'Type': 'AAA'
            },      
        ]
    },
    'BBB': {
        'C1': [
            {
                'Name': 'C1',
                'Value': 10,
                'Type': 'BBB'
            }   
        ],
        'D1': [
            {
                'Name': 'D1',
                'Value': 10,
                'Type': 'BBB'
            },      
        ]   
    }
}

To achieve this, so far i have tried looping over the whole data and then splitting them into separate objects based on the "Type" and then create a unique list of "Name", then iterating over the newly created objects to split them based on the Name.

I was doing something like this,

tTmp_List_1 = []
tTmp_List_2 = []

tTmp_Name_List_1 = []
tTmp_Name_List_2 = []

for tValue in Data:
    if (tValue['Type'] == 'AAA'):
        tTmp_List_1.append(tValue)
        tTmp_Name_List_1.append(tValue['Name'])

    if (tValue['Type'] == 'BBB'):
        tTmp_List_2.append(tValue)  
        tTmp_Name_List_2.append(tValue['Name'])          

tTmp_Name_List_1 = list(set(tTmp_Name_List_1))
tTmp_Name_List_2 = list(set(tTmp_Name_List_2))

From the above "tTmp_Name_List_1" and "tTmp_Name_List_2", i am about to iterate over the list and then match the matching names with the initial Data object to come up with separated list objects based on the names and then set it back with something like this

tTmp_Dict = {}
for tTmp_Name in tTmp_Name_List_1 :
    tTmp = []
    if (Data['Name'] == tTmp_Name):
        tTmp.append(Data)
    
    tTmp_Dict.append(tTmp)

Can someone kindly suggest me or help me with a more better way of doing this.

Any help is much appreciated.

Thanks,

I have JSON object something like below,

Data = [
    {
        'Name': 'A1',
        'Value': 10,
        'Type': 'AAA'
    },
    {
        'Name': 'A1',
        'Value': 20,
        'Type': 'AAA'
    },  
    {
        'Name': 'B1',
        'Value': 10,
        'Type': 'AAA'
    },
    {
        'Name': 'C1',
        'Value': 10,
        'Type': 'BBB'
    },
    {
        'Name': 'D1',
        'Value': 10,
        'Type': 'BBB'
    }
]

And i would like to split the object into a list based on "Type" and then based on the "Name" also to something like below,

Data = {
    'AAA': {
        'A1': [
            {
                'Name': 'A1',
                'Value': 10,
                'Type': 'AAA'
            },
            {
                'Name': 'A1',
                'Value': 20,
                'Type': 'AAA'
            },          
        ],
        'B1': [
            {
                'Name': 'B1',
                'Value': 10,
                'Type': 'AAA'
            },      
        ]
    },
    'BBB': {
        'C1': [
            {
                'Name': 'C1',
                'Value': 10,
                'Type': 'BBB'
            }   
        ],
        'D1': [
            {
                'Name': 'D1',
                'Value': 10,
                'Type': 'BBB'
            },      
        ]   
    }
}

To achieve this, so far i have tried looping over the whole data and then splitting them into separate objects based on the "Type" and then create a unique list of "Name", then iterating over the newly created objects to split them based on the Name.

I was doing something like this,

tTmp_List_1 = []
tTmp_List_2 = []

tTmp_Name_List_1 = []
tTmp_Name_List_2 = []

for tValue in Data:
    if (tValue['Type'] == 'AAA'):
        tTmp_List_1.append(tValue)
        tTmp_Name_List_1.append(tValue['Name'])

    if (tValue['Type'] == 'BBB'):
        tTmp_List_2.append(tValue)  
        tTmp_Name_List_2.append(tValue['Name'])          

tTmp_Name_List_1 = list(set(tTmp_Name_List_1))
tTmp_Name_List_2 = list(set(tTmp_Name_List_2))

From the above "tTmp_Name_List_1" and "tTmp_Name_List_2", i am about to iterate over the list and then match the matching names with the initial Data object to come up with separated list objects based on the names and then set it back with something like this

tTmp_Dict = {}
for tTmp_Name in tTmp_Name_List_1 :
    tTmp = []
    if (Data['Name'] == tTmp_Name):
        tTmp.append(Data)
    
    tTmp_Dict.append(tTmp)

Can someone kindly suggest me or help me with a more better way of doing this.

Any help is much appreciated.

Thanks,

Share Improve this question edited Nov 20, 2024 at 6:29 SM079 asked Nov 20, 2024 at 5:28 SM079SM079 7553 gold badges11 silver badges32 bronze badges 2
  • 1 I see that you have edited your question after my answer, to change the output to a list. you cant have a key:value pair inside a list. You will get a syntax error, Key-value pairs not allowed inside a list. – Nesi Commented Nov 20, 2024 at 6:25
  • okay, understood.. Thank you – SM079 Commented Nov 20, 2024 at 6:29
Add a comment  | 

3 Answers 3

Reset to default 1

Try this.

anized_data = {}
for item in Data:
    item_type = item['Type']
    item_name = item['Name']
    
    if item_type not in anized_data:
        anized_data[item_type] = {}
    
    if item_name not in anized_data[item_type]:
        anized_data[item_type][item_name] = []
    
    anized_data[item_type][item_name].append(item)

# Output the anized data
print(anized_data)
from collections import defaultdict
data = 'your nested dict'

output_dict = defaultdict(lambda: defaultdict(list))
for element in data:
    output_dict[element['Type']][element['Name']].append(element)
    
output = {k : dict(v) for k, v in output_dict.items()}
print(output)

Try this

for item in Data:
    result.setdefault(item['Type'], {}).setdefault(item['Name'], 
       []).append(item)

The setdefault method simplifies the creation of nested dictionaries by initializing keys if they don’t exist.

发布评论

评论列表(0)

  1. 暂无评论