miércoles, 31 de julio de 2024

finding dict key based on the value

st={'Ambiorix':90,'Katherine':89,'Armando':88,'Ruth':97}


names=list(st.keys())

scores=list(st.values())

print(names,scores)



def getmax(dct,p):

    names=list(dct.keys())

    scores=list(dct.values())

    post=scores.index(p)

    print(f' Found {names[post]} with score {p} in position {post}')

getmax(st,90)



['Ambiorix', 'Katherine', 'Armando', 'Ruth'] [90, 89, 88, 97]

 Found Ambiorix with score 90 in position 0



Chatgpt improve version


st = {'Ambiorix': 90, 'Katherine': 89, 'Armando': 88, 'Ruth': 97}


names = list(st.keys())

scores = list(st.values())


print(names, scores)


def getmax(dct, p):

    if p in dct.values():

        for name, score in dct.items():

            if score == p:

                post = scores.index(p)

                print(f'Found {name} with score {p} in position {post}')

                break

    else:

        print(f'Score {p} not found in the dictionary.')


getmax(st, 90)


No hay comentarios:

Publicar un comentario