3

I want to search a python dictionary for a key that matches an initial sequence of letters. However, it's a bit more complicated and I lost myself midway in confusion.

Example: I have a string "ABSTTHGIHG" and i want to search a dictionary for a key that matches exactly the last 9 letters of the string. If none is found i want to search another dictionary for a key that matches exactly the last 8 letters of the string.

I have no idea how to match a specific number of letters (here "the last x letters") with a key (or how to search for a key) so i have hopes that somebody here can perhaps name a function that enables me to do so or where i can look it up. There is no code that i can present since this would be the first thing the program does. Can i specify "the last 9 letters" with something like x = string[1:]? That would be the only idea i have how to specify which letters of the string to use for the search.

grindbert
  • 173
  • 1
  • 2
  • 15

3 Answers3

4

Since dictionaries are hashed tables, you can't just look them up by the last bit of the key like you would the whole key. Instead you have to iterate over the keys

for key in dictionary.keys():
    if key[-9:] == 'BSTTHGIHG':
        print('I found it!!')
        break

Note the use of key[-9:]

randomusername
  • 7,927
  • 23
  • 50
1
st = "ABSTTHGIHG"

for x in range(1,len(st)):
    for key in dictionary.keys():
        if st[x:] == key:
            #do something with your key
        print(st[x:])

that's how you can get last x letters of your stirng

out

BSTTHGIHG
STTHGIHG
TTHGIHG
THGIHG
HGIHG
GIHG
IHG
HG
G

so you have last 9 letters, 8, 7....

Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31
1

an element in the dictionary looks like {'key' , 'value'} keys are unique within dictionary while values may be not. assume your dictionary looks like

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

so to get the value corresponding to any key , you can do so by :

print dict['Name'] # which will display 'Zara'

now regarding strings , if you have val = "ABCDEFGH" and you want to get substring from index 1 to the end you can do so by :

val = "ABCDEFGH"
print val[1:] # this will display "BCDEFGH"
print val[2:] # this will display "CDEFGH"
# A negative index accesses elements from the end of the list counting backwards.
print val[-1:] # this will display "H"
print val[-3:] # this will display "FGH" 

so for your example you want to search a dictionary for a key that matches exactly the last 9 letters of the string

st = "ABSTTHGIHG"
print dict[st[-9:]] # this will display the value corresponding to the key "BSTTHGIHG" if it exists
Moataz Shawky
  • 79
  • 1
  • 3