简体   繁体   中英

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())))

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM