-4

How can i search a variable from a multi key dict and get the respective value in python?

dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}

var = '1502'

output

should be a2g3

  • A dictionary is designed for lookups by the *full* key. Any other lookup is going to be inefficient. If the actual size of the dictionary is large and there are multiple lookups it might be a good idea to reshape the data structure to allow efficient lookups. – Klaus D. Mar 31 '18 at 05:18
  • Possible duplicate of [Python dictionary: Get list of values for list of keys](https://stackoverflow.com/questions/18453566/python-dictionary-get-list-of-values-for-list-of-keys) – Narendra Mar 31 '18 at 05:18
  • Whether there's a solution or not, the tuple/list used as key doesn't ensure the unicity of the keys/sub-keys. Using such a thing likely will produce a disaster. – Gergely M Mar 16 '20 at 10:33

3 Answers3

0

Just iterate over the keys and find

   print([dict1[i] for i in dict1.keys() if var in i])
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • 1
    Code only answer is not helpful – Munim Munna Mar 31 '18 at 05:50
  • Correct me if I'm wrong, but this snippet just degrades the dict (hashmap) lookup time complexity from O(1) to O(n) and will return a list of a single value or empty list. It seems to be just replicating `dict1.get(var)` wrapped in a list. – Gergely M Mar 16 '20 at 10:11
  • @GergelyM It will return a list of tuples. – Smart Manoj Mar 16 '20 at 12:30
  • It returns a string as a single item list - but iterates the whole Dictionary even if it found one -> so it's a certain O(n) lookup. This solution would return multiple items if the key is repeated in the non-unique keys -> `('1700','1502','3700')` or `('1502','1518')` or `('1502')` are perfectly valid and unique keys, although each has the value of `var`, thus the snippet will return 3 values as a list... Otherwise, I'd prefer your answer as the solution above the others. – Gergely M Mar 17 '20 at 10:06
  • 1
    It will return as you said only – Smart Manoj Mar 17 '20 at 12:55
0

One way:

dict1 = {('1700','2700','3700'): 'a3g3',
         ('1502','1518'): 'a2g3',
         ('2600'): 'a3g2'}

print(next(v for k, v in dict1.items() if '1502' in k))
# a2g3
Austin
  • 25,759
  • 4
  • 25
  • 48
0

List comprehension is good approach ,

Here is Filter approach just for fun : You can filter the result :

dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}

var = '1502'
print(dict1[list(filter(lambda x:var in x,dict1.keys()))[0]])

output:

a2g3
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88