Get keys from a dicionary

alex23 wuwei23 at gmail.com
Mon Nov 14 00:42:59 EST 2011


On Nov 11, 11:31 pm, macm <moura.ma... at gmail.com> wrote:
>
> I pass a nested dictionary to a function.
>
> def Dicty( dict[k1][k2] ):
>         print k1
>         print k2
>
> There is a fast way (trick) to get k1 and k2 as string.

It might be possible to do something using a reverse dictionary and
getting rid of the nested dictionary.

This is a quick and simple 'two-way' dictionary class that works by
maintaining two dictionaries: the original key/value, and the reversed
value/key. It returns a list of keys, allowing for a value to be
assigned against more than

    from collections import defaultdict

    class TwoWayDict(dict):
        def __init__(self, *args, **kwargs):
            self._reversed = defaultdict(list)
            for key, val in kwargs.iteritems():
                self[key] = val

        def __setitem__(self, key, value):
            super(TwoWayDict, self).__setitem__(key, value)
            self._reversed[value].append(key)

        def getkeys(self, match):
            return self._reversed[match]

    >>> original = TwoWayDict(a=100,b='foo',c=int,d='foo')
    >>> original.getkeys(100)
    ['a']
    >>> original.getkeys('foo')
    ['b', 'd']

As for the nested dictionary, you could replace it with a _single_
dictionary that uses a composite key:

    >>> original = TwoWayDict(a=100,b=100)
    >>> original.getkeys(100)
    ['a', 'b']
    >>> original = TwoWayDict()
    >>> original['record1','user1'] = 'martin'
    >>> original['record1','user2'] = 'robert'
    >>> original['record2','user1'] = 'robert'
    >>> original.getkeys('robert')
    [('record1', 'user2'), ('record2', 'user1')]

> Whithout loop all dict. Just it!

The TwoWayDict class removes the need to loop across the dict looking
for keys that match a value by replacing it with another dict lookup.
Reducing the nested dict to a single dict with composite keys removes
the need to traverse the outer dict to compare against its children.



More information about the Python-list mailing list