Home > Net >  Find a value in dictionary by coordinates
Find a value in dictionary by coordinates

Time:11-26

I want to be able to find a certain place in a dictionary by its coordinates/place. If let's say the key is x, and each character represents a y-value, I want to be able to find what a certain character in a place is in the dictionary by asking for inputs for which place I am looking for.

Ex

1: 'Hi' 
2: 'My name is Stan'
3: 'What is your name?' 

If you would put in the places:

(1,0) = 'H' # the H in 'Hey' 
(4,1) = Out of bounds # since key 4 do not exist
(1,2) = Out of bounds #since there is nothing after 'Hi'
(2,2) = Space #in between 'My' and 'name' 
(3,3) = t # the t in 'What'

I have tried to mix around with some if loops, but without any good results. I assume I could use some function like len() to find the length of characters assigned to each key, but not been able to execute this fully.

Have something like this as a start but it needs more.

for key, value in indexed_file.items():
    if key != row:
        print('Out of bounds')

Any tips on how I can proceed to execute this is really valuable. Note: I do not want to use any import.

CodePudding user response:

You can slice the dictionary/list and use try/except to catch IndexError (and KeyError):

d = {1: 'Hi',
     2: 'My name is Stan',
     3: 'What is your name?' }

def get_letter(key, pos):
    try:
        print(d[key][pos])
    except IndexError:
        print('Out of bounds!')
    except KeyError:
        print('No Key!')

Example:

>>> get_letter(1,0)
H

>>> get_letter(2,15)
Out of bounds!

If you want to have the same outcome for both IndexError and KeyError:

def get_letter(key, pos):
    try:
        print(d[key][pos])
    except (IndexError, KeyError):
        print('Out of bounds!')

CodePudding user response:

I would do it rather simple;

d= {1:"Hi",2:"My name is stan", 3:"What is your name?"}
input_cords = (1,1)

sent = input_cords[0] #Get sentence
if d.get(sent):
   try:
       res = d[sent][input_cords]
   except IndexError:
       print("out of bounds")
else: 
    print("No key")

CodePudding user response:

For fun without error handling

dct = {1: 'Hi', 2: 'My name is Stan', 3: 'What is your name?'}

x, y = 3, 0
l = s[y:y   1] if (s := dct.get(x, '')) else ''
print(l if l else 'Out of bounds')
W

CodePudding user response:

You could use the get method on the dictionary and a subscript on the string to obtain a character and, if none is accessible, return the out of bounds string:

def getLetter(d,k,i):
    return d.get(k,"")[i:i 1] or 'Out of Bounds'
  • Related