searching a value of a dict (each value is a list)

Adonis Vargas adonisv at REMOVETHISearthlink.net
Sun Dec 9 22:18:33 EST 2007


Seongsu Lee wrote:
> Hi,
> 
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
> 
> dict = {1: [1, 2, 3, 4, 5],
>    2: [10, 11, 12],
>    900000: [100, 101, 102, 103, 104, 105],
>    900001: [20, 21, 22],
>    999999: [15, 16, 17, 18, 19]}
> 
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 900000 must be returned.
> 
> How can I do this with Python? Ideas?

You can try this:

items = {1: [1, 2, 3, 4, 5],
          2: [10, 11, 12],
          900000: [100, 101, 102, 103, 104, 105],
          900001: [20, 21, 22],
          999999: [15, 16, 17, 18, 19]}

def findItem(item, dictionary):
     for key, value in dictionary.iteritems():
         if item in value:
             print key, value

findItem(104, items)

This will allow you to work with the existing dataset without needing to 
duplicate it. It will print all occurrances.

Also, you should never use reserved words like 'dict' this creates 
confusion and can cause Python to misbehave since you are rebinding the 
name.

Hope this helps.

Adonis Vargas




More information about the Python-list mailing list