Home > Enterprise >  Making nested dictionary object from dictionary in python
Making nested dictionary object from dictionary in python

Time:09-27

I am trying to build a response object in dictionary from a database query result. My data is look like this from the query result.

data = [
    {
        "form": "form-name",
        "path": "/errr",
        "category": "cat1"
    },
    {
        "form": "form-name",
        "path": "/ddf/",
        "category": "cat1"
    },
    {
        "form": "form-name",
        "path": "/qqq",
        "category": "cat2"
    },
    {
        "form": "form-name",
        "path": "/www",
        "category": "cat2"
    },

]

I want to make another dataset like this please see the example.

[
   { 
       "cat1" : [

            {
            "form": "form-name",
            "path": "/kllk",
            },
            {
            "form": "form-name",
            "path": "/wer",
            },

       ],
       "cat2" : [

            {
            "form": "form-name",
            "path": "/yuje",
            },
            {
            "form": "form-name",
            "path": "/tyyy",
            },

       ]
   }

]

So far I took the category out from the first dataset and store in a list and run a function to make it unique category.

c = []
for d in data:
    if d['category']:        
        c.append(d['category'])

# Function to make a unique category not to duplicate
def unique_value(value):
    unique_value_string = []
    myvalue = set(value)

    for v in myvalue:
        unique_value_string.append(v)

    return unique_value_string
keys = unique_value(c)

k = keys

d = dict(zip(k, data))

#this is final result 
{'cat2': {'form': 'form-name', 'path': '/errr', 'category': 'cat1'}, 'cat1': {'form': 'form-name', 'path': '/ddf/', 'category': 'cat1'}}
final keys: ['cat2', 'cat1']

As you can see it is not correct. Please suggest me any better solution.

Thanks in advance

CodePudding user response:

Try:

data = [
    {"form": "form-name", "path": "/errr", "category": "cat1"},
    {"form": "form-name", "path": "/ddf/", "category": "cat1"},
    {"form": "form-name", "path": "/qqq", "category": "cat2"},
    {"form": "form-name", "path": "/www", "category": "cat2"},
]

out = {}
for d in data:
    out.setdefault(d["category"], []).append(d)

for d in out.values():
    for v in d:
        del v["category"]

print([out])

Prints:

[
    {
        "cat1": [
            {"form": "form-name", "path": "/errr"},
            {"form": "form-name", "path": "/ddf/"},
        ],
        "cat2": [
            {"form": "form-name", "path": "/qqq"},
            {"form": "form-name", "path": "/www"},
        ],
    }
]
  • Related