4

This dict structure :

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

should become this dict structure:

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

I have 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 any way to simplify my approach. I am using python 3.5

2 Answers 2

4

You can solve it with a defaultdict(list), iterating over the categories and appending keys:

>>> 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']}
2
  • Additional import :(
    – Skeec
    Commented Sep 1, 2016 at 17:32
  • @Skeec so? It leads to a much more readable implementation. Besides, it's a built-in, it always is available. Commented Sep 1, 2016 at 19:14
2
if 'category' in value:

This line makes sure that the key category is in the dictionary, before using it. Then you get the value from the dictionary corresponding to category and iterate it. You can simplify this with dict.get method, which would return a default value, if the key is not there in the dictionary. So you can do something like this

for cat in value.get('category', []):

If the category doesn't exist in the dictionary, then an empty list is returned and the loop will have nothing to iterate.


Similarly, you are checking if the key exists in the categories dictionary, if not, setting a default value (which is a list). You can avoid that if...else also, with dict.setdefault, like this

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

dict.setdefault is similar to dict.get, except that it sets the default value against the key and returns the value corresponding to the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.