Searching Dictionary

Simon Forman sajmikins at gmail.com
Wed Sep 23 16:34:18 EDT 2009


On Wed, Sep 23, 2009 at 2:31 PM, Support Desk
<support.desk.ipg at gmail.com> wrote:
>
> i am trying to search a large Python dictionary for a matching value. The
> results would need to be structured into a new dictionary with the same
> structure. Thanks.
>
> The structure is like this
>
> { Key : [{'item':value,'item2':value,'
> item3':value,'item4':value,'item5':value','item6':value,'item7':value,'item8':value,'item9':value}],
> Key2 :
> [{'item':value,'item2':value,'item3':value,'item4':value,'item5':value','item6':value,'item7':value,'item8':value,'item9':value}],
> Key3 :
> [{'item':value,'item2':value,'item3':value,'item4':value,'item5':value','item6':value,'item7':value,'item8':value,'item9':value}]
> }

There is not really enough information to answer your query directly.
But I'll take a guess anyway.


First, let's put your in a piece of code that will actually run (which
is what you shourd have done in the first place..):



Key = Key2 = Key3 = value = 42

D = {
    Key: [
        {'item':value,
         'item2':value,
         'item3':value,
         'item4':value,
         'item5':value,
         'item6':value,
         'item7':value,
         'item8':value,
         'item9':value}
        ],
    Key2: [
        {'item':value,
         'item2':value,
         'item3':value,
         'item4':value,
         'item5':value,
         'item6':value,
         'item7':value,
         'item8':value,
         'item9':value}
        ],
    Key3: [
        {'item':value,
         'item2':value,
         'item3':value,
         'item4':value,
         'item5':value,
         'item6':value,
         'item7':value,
         'item8':value,
         'item9':value}
        ]
    }

Now let's write a function that (maybe) does what you (kind of) specified:

def wtf(d, match_me):
    result = {}
    for key, value in d.iteritems():
        inner_dict = value[0]
        for inner_key, inner_value in inner_dict.iteritems():
            if inner_value == match_me:
                result[key] = [{inner_key: inner_value}]
    return result


And let's try it:

print wtf(D, 42)

That prints:

{42: [{'item': 42}]}


Is that what you're asking for?



More information about the Python-list mailing list