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

Seongsu Lee senux at senux.com
Sun Dec 9 11:50:06 EST 2007


On 12월10일, 오전1시23분, Seongsu Lee <se... at senux.com> 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?

Hi,

I just let the dict work in bidirectional fashion so that
I can find out what I want by both key and value. A mark
or prefix was needed to distinguish between keys originated
from keys and keys originated from values. (value * (-1))

from pprint import pprint
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]}
for k, v in dict.items():
        for x in v:
                dict[x * -1] = k
pprint(dict)

{-105: 900000,
 -104: 900000,
 -103: 900000,
 -102: 900000,
 -101: 900000,
 -100: 900000,
 -22: 900001,
 -21: 900001,
 -20: 900001,
 -19: 999999,
 -18: 999999,
 -17: 999999,
 -16: 999999,
 -15: 999999,
 -12: 2,
 -11: 2,
 -10: 2,
 -5: 1,
 -4: 1,
 -3: 1,
 -2: 1,
 -1: 1,
 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]}

What do you think of this? Ideas with less space complexity?



More information about the Python-list mailing list