if 'category' in value:
This line ensures that the key categoryis in the dictionary before using it. Then you get the value from the dictionary matching category, and repeat it. You can simplify this with a method dict.getthat will return the default value if there is no key in the dictionary. So you can do something like this
for cat in value.get('category', []):
If it categorydoes not exist in the dictionary, an empty list is returned, and the loop will not have anything iterated.
, , categories, , ( ). if...else , dict.setdefault,
categories = {}
for key, value in data.items():
if isinstance(value, dict):
for cat in value.get('category', []):
categories.setdefault(cat, []).append(key)
dict.setdefault dict.get, , , .