Sathya Varna
Sathya Varna

Reputation: 13

Return specific value for each value in a list

I want to return a specific value for each value in a list.

list = ['sathya','varna','summi']

I want to return values such that if my key is 'sathya' return -5, if key is 'varna' return -4.

As of now my code is:

def return_value():
   if key == 'sathya':
         return -5
   if key == 'varna':
         return -4

But I don't want to use so many if conditions. can anyone help me in this

Upvotes: 0

Views: 786

Answers (4)

user459872
user459872

Reputation: 24562

You can use enumerate if the return value is their index.

your_list = ['sathya','varna','summi']

Method 1

def return_value(key):
    for index, key_ in enumerate(your_list, start=-5):
        if key == key_:
            return index
    return "Not found"

print(return_value('sathya')) # return -5
print(return_value('invalid item')) # return not found

Method 2(Using Dict Comprehension)

def return_value(key):
    return {
            value: index 
            for index, value in enumerate(your_list ,start=-5)
           }.get(key, "Not found")

print(return_value('sathya')) # return -5
print(return_value('invalid item')) # return not found

Upvotes: 0

00__00__00
00__00__00

Reputation: 5327

The basic python data structure you are looking for is a dictionary, not a list. Dictionaries allow key-value pairing in a native way. Example.

d={akey:aval}
d['mykey']=myval

then you can retrieve you values

print(d['mykey'])

Upvotes: 0

Frank AK
Frank AK

Reputation: 1781

try to use dict instead of loop check condition:

list = ['sathya','varna','summi']

name_to_id = {'sathya':-5,'varna':-4,'summi':-3}
for i in list:
    return name_to_id.get(i)

Upvotes: 0

Aleksei Maide
Aleksei Maide

Reputation: 1855

Use a dictionary to store the values and access by key.

def return_value(key):
    return {'sathya': -5,'varna': -4,'summi': 'any value..'}[key]

Upvotes: 2

Related Questions