Python syntax. Beautiful, right, short code
Question: 
    for item in listOfModels:
        if item[0] in perms:
            perms[item[0]][item[1]] = True
        else:
            perms[item[0]] = {item[1]: True}
    

I often use code like this. Please tell me beautiful, short, right way to do
same.

(lib's, books, samples, etc.)

E.G. i have

    
    
    [
        ['animal', 'rabbit'],
        ['animal', 'cow'],
        ['plant', 'tree'],
        ['animal', 'elephant'],
        ['fruit', 'strawberry'],
        ['fruit', 'apple'],
    ]
    

and need

    
    
    {
        'animal': ['rabbit', 'cow', 'elephant'],
        'plant': ['tree'],
        'fruit': ['strawberry', 'apple'],
    }
    

OR

    
    
    {
    'animal': {
        'rabbit': True,
        'cow': True,
        'elephant': True
    },
    'plant': {
        'tree': True
    },
    'fruit': {
        'strawberry': True,
        'apple': True
    },
    


Answer: Two options: use
[`dict.setdefault()`](https://docs.python.org/2/library/stdtypes.html#dict.setdefault)
or use a [`collections.defaultdict()`
object](https://docs.python.org/2/library/collections.html#collections.defaultdict).

Using `dict.setdefault()`:

    
    
    for category, name in listOfModels:
        perms.setdefault(category, {})[name] = True
    

or using a `defaultdict`:

    
    
    from collection import defaultdict
    
    perms = defaultdict(dict)
    for category, name in listOfModels:
        perms[category][name] = True
    

`dict.setdefault()` looks up the key for you, and if it is missing uses the
second argument to set the value. That way you _always_ get a dictionary back
(even an empty one), on which you can then set the `name` key.

A `defaultdict` takes a factory argument, and each time a key you try to
access is missing, the factory is called to produce a default value. So
accessing `perms['missing_key']` has the same effect as using
`perms.set_default('missing_key', default)`; a new value is produced as
needed.

Either method is trivially adapted to produce lists or sets instead of a
dictionary with `True` values:

    
    
    # producing a list
    for category, name in listOfModels:
        perms.setdefault(category, []).append(name)
    
    # or a set
    for category, name in listOfModels:
        perms.setdefault(category, set()).append(name)
    
    # same with defaultdict
    perms = defaultdict(list)
    for category, name in listOfModels:
        perms[category].append(name)
    
    perms = defaultdict(set)
    for category, name in listOfModels:
        perms[category].add(name)
    

Sets are probably the best option here, being the direct equivalent of the
dictionary with values set to `True`.

