P
P
pcdesign2020-09-18 13:27:14
Python
pcdesign, 2020-09-18 13:27:14

How to merge a struct within a struct?

Here is such a structure:

[
  {
    "cat_name":"Распродажа",
    "sub_cats":[
      {
        "cat_name":"aaaaa",
        "goods_inside":[
          "00-00004044",
          "00000000325"
        ]
      },
      {
        "cat_name":"bbbbbb",
        "goods_inside":[
          "00-00001816"
        ]
      }
    ]
  },
  {
    "cat_name":"aaaaa",
    "goods_inside":[
      "00-00003108"
    ]
  },
  {
    "cat_name":"bbbbbb",
    "goods_inside":[
      "00-00001814",
      "00-00004288"
    ]
  }
]


How to get to this one:
[
  {
    "cat_name":"aaaaa",
    "goods_inside":[
      "00-00003108", "00-00004044", "00000000325"
    ]
  },
  {
    "cat_name":"bbbbbb",
    "goods_inside":[
      "00-00001814", "00-00004288",  "00-00001816"
    ]
  }
]


That is, what is in the "Sale" section is thrown into the appropriate subsections, and the "Sale" itself is deleted.
from collections import defaultdict? Or is it better somehow differently?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aRegius, 2020-09-18
@pcdesign

As an option:

cat_goods_dict = defaultdict(list)

for d in data[0]['sub_cats'] + data[1:]:
    cat_goods_dict[d['cat_name']] += d['goods_inside']

new_data = [
    {'cat_name': cat_val, 'goods_inside': goods_val}
    for cat_val, goods_val in cat_goods_dict.items()
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question