Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List of Tuples (Find value with key + check if exist)

I have a list of tuples wich is:

TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]

And what i want to do is get the value printed out if i have the key

Like:

x = raw_input("Word to lookup: ") # I insert "computer"

and it should print out "weird working machine"

TD LR: Get the Value with the Key

Another thing i need to fix is that if i try to append the Tuple with a new word that ALREADY exists in the tuple it should print "Already exists" else it should append with the new word. Something like this:

if(word in tuple exist)
    print "Already exist"
else
    TupleOrd.append(((raw_input("\n Word to insert: ").lower()),(raw_input("\n Description of word: ").lower())))
like image 925
Widdin Avatar asked Oct 19 '25 13:10

Widdin


2 Answers

Tuples aren't the greatest data type for key-value lookup. Consider using a dictionary instead:

>>> TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]
>>> d = dict(TupleList)
>>> d["computer"]
'weird working machine'

It also makes it easier to check for the presence of existing words:

key = raw_input("Word to insert:").lower()
if key in d:
    print "Sorry, that word is already present"
else:
    d[key] = raw_input("Description of word:").lower()

If you absolutely must use a tuple, you can search for keys with a loop:

for key, value in TupleList:
    if key == "computer":
        print value

and similarly determine which keys already exist:

key_exists = False
for key, value in TupleList:
    if key == "computer":
        key_exists = True
if key_exists:
    print "Sorry, that word is already present"
else:
    #todo: add key-value pair to tuple
like image 147
Kevin Avatar answered Oct 22 '25 13:10

Kevin


One crazy way to do this would be:

TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]
x = raw_input("Word to lookup: ")
key_exists = next(iter([i[1] for i in TupleList if i[0] == x]), None)) is not None
if key_exists:
    print 'key exists'
like image 35
Guilherme David da Costa Avatar answered Oct 22 '25 12:10

Guilherme David da Costa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!