Transform Dictionary

This dict structure:

data = {
    'a': { 'category': ['c', 'd'] },
    'b': { 'category': ['c', 'd'] }
}

should become this structure:

data = {
    'c' : ['a', 'b'],
    'd' : ['a', 'b']
}

I have the following approach:

for key, value in data.items():
    if isinstance(value, dict):
        if 'category' in value:
            for cat in value['category']:
                if cat in categories:
                    categories[cat].append(key)
                else:
                    categories[cat] = [key]

I want to know if there is a way to simplify my approach. I am using python 3.5

+4
source share
2 answers
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, , , .

+2

defaultdict(list), :

>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>> for key, value in data.items():
...     for item in value['category']:
...         d[item].append(key)
... 
>>> dict(d)
{'c': ['a', 'b'], 'd': ['a', 'b']}
+4

Source: https://habr.com/ru/post/1653344/


All Articles