Home > Back-end >  Is there any Pythonic way to manipulate Dictionaries to follow DRY philosophy in Django?
Is there any Pythonic way to manipulate Dictionaries to follow DRY philosophy in Django?

Time:02-20

I have got dictionary set of required queries as shown below:

[
    {
        "primary_attribute__name": "Color"
        "primary_attr_values__name": "Red",
    },
    {
        "primary_attribute__name": "Color",
        "primary_attr_values__name": "Green",
    },
]

Now I want :

[
    {
        "primary_attribute__name": "Color"
        {
            "primary_attr_values__name": "Red",
            "primary_attr_values__name": "Green",
            "primary_attr_values__name": "Yellow",
        },
    }
]

Or is this good approach:

primary_attribute = {
    "Color": {
        "primary_attr_values__name": [
            "red",
            "green",
            "yellow",
        ]
    }
}

How it can be achieved?

Edit: Actually I have Product, Product has Variant and each Variant may have VariantAttributes. VariantAttributes has primary_attr, primary_aatr_value ( these are like color: green, color:red, color:green)

For that Product; ProductVariant's ProductAttribute primary_attr_name will be same, for example : Color, but the values will be different on each variant. I am trying to solve this condition with dictionary.

CodePudding user response:

It's somewhat hard to tell what you really want here, but if my guess is correct...

Given data like you have, if you want to group it to an attribute -> values mapping, it's easy to do with a defaultdict:

from collections import defaultdict

data = [
    {
        "primary_attribute__name": "Color",
        "primary_attr_values__name": "Red",
    },
    {
        "primary_attribute__name": "Color",
        "primary_attr_values__name": "Green",
    },
    {
        "primary_attribute__name": "Color",
        "primary_attr_values__name": "Blue",
    },
    {
        "primary_attribute__name": "Shape",
        "primary_attr_values__name": "Circle",
    },
    {
        "primary_attribute__name": "Shape",
        "primary_attr_values__name": "Rectangle",
    },
]

attribute_values = defaultdict(list)

for datum in data:
    attr_name = datum["primary_attribute__name"]
    attr_value = datum["primary_attr_values__name"]
    attribute_values[attr_name].append(attr_value)

print(dict(attribute_values))

This outputs

{'Color': ['Red', 'Green', 'Blue'], 'Shape': ['Circle', 'Rectangle']}
  • Related