1

Similar to this Get Key by value question but this time, the value is inside an array. The solution i think of is loop each item the Dictionary, and loop again for each items in the value pair. But from the looks of it, this is intensive. Is this the only way?

# a dictionary that contains ranges. this dictionary might have 1million keys and the range can have many values too
dictionary = {
            "x": range(0,10),
            "y": range(11,20),
            "z": range(21,30)
            .
            .
            .
        }
get_dictionary_value = 16
for k,v in dictionary.items():
    for item in v:
        if get_dictionary_value = item:
            print("the key is {}".format(k)) #the output will be "the key is y"
Led
  • 662
  • 1
  • 19
  • 41
  • 1
    Why not just `for k, v in dictionary.items(): if get_dictionary_item in v: print(...)`? You can also `break` at that point if there'll only be one key. You could also consider alternative data structures (even just a reversed dictionary) if you do this a lot. – jonrsharpe Jun 12 '19 at 10:31
  • @jonrsharpe thanks, what do you think is the better approach in this? – Led Jun 12 '19 at 11:17

2 Answers2

1

This is a typical use-case for next():

dictionary = {
            "x": range(0,10),
            "y": range(11,20),
            "z": range(21,30)
        }

get_dictionary_value = 16

next(k for k,v in dictionary.items() if get_dictionary_value in v, 'No match')

Returns:

y
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • is this memory intensive? I know iterators is better than conventional loops – Led Jun 12 '19 at 11:20
  • 1
    Not sure exactly in what perspective but this should with python3 be a loop over a generator. So quick answer: no. – Anton vBR Jun 12 '19 at 11:35
1

To stick with your approach you can use the in-statement as @Anton vBR mentioned. This checks if some item is included in a data structure (works not just on lists)

d = {
    "x": range(0,10),
    "y": range(11,20),
    "z": range(21,30)
}

query = 16
for k,v in d.items():
    if query in v: k

>>> 'y'

will return the key that matches your query

turnman
  • 154
  • 10
  • I have no issues running this, but im just wondering if this is memory intensive. – Led Jun 12 '19 at 11:18