简体   繁体   中英

How to compare array entries to dictionary keys and return a dictionary value

I am trying to make a python program that takes user input text or a file and changes each character into a value and then returns the result. I have a user string that being read into a list. I am trying to have a for loop go through that list and check each character against a dictionary key and then return the value in the dictionary. How would i go about doing that? Thanks

Code so far:

for i in range (0, len(text)): 
    for j in alphabet.keys(): 
        if text[i].upper() == alphabet.values(): 
            j+=1
            print(alphabet.items()) 
    i+=1
for item in list_:
    try:
        print(d[item])
    except KeyError as e:
        print("{} not in d".format(e.args[0]))

Without seeing your code, I can't offer anything more relevant

You probably want to use string.maketrans and string.translate

>>> import string
>>> table = string.maketrans('abc', 'xyz')
>>> string.translate('the cat is bad', table)
'the zxt is yxd'

Most of the code below is simply to create the dictionary that translates letters of an input into randomised corresponding values in a dict (ie each letter maps to another random letter). Points on your code:

1) range() automatically defaults to starting at 0 so range(0, n) is better just written as range(n)

2) You don't need to use range() at all here. for letter in string will take an input string and go through it, letter by letter. for elephant in string will do the same, each letter is being assigned to the name elephant in turn, so the fact that I chose to use letter instead is simply for readability.

3) Using keys() , values() and items() is not the way to query a dictionary. You have two standard approaches; I could use translation_dict[letter] which will throw KeyError if the value of letter is not a key in the dictionary, or translation_dict.get(letter) which will return None if the key doesn't exist. In the below example, I used get() but also added another parameter ("not in dict") which replaces None as the default value if the letter isn't found as a key.

import string # For setup of example data
import random # For setup of example data

# Just creating the translation dictionary and fake user input
alphabet = list(string.uppercase)
translated = random.sample(alphabet, len(alphabet))
translation_dict = {i: j for i, j in zip(alphabet, translated)}

user_input = 'Hello'

# The loop you're trying

for letter in user_input:
    corresponding_value = translation_dict.get(letter.upper(), 'Not in dict')
    print(corresponding_value)

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