-3

I have set up a simple dictionary of the form:

dictionary = {'T':'1','U':'2','V':'3')

what i am trying to do is iterate through a message and with the following code, swap every instance of a number with an associated key value.

for character in line:
            if character in dictionary and character.isalpha() !=True:
                equivalent_letter = dictionary(key??)

Any ideas?

Tiny
  • 409
  • 2
  • 8
  • 20

4 Answers4

3

If you're likely to use the mapping in reverse often, I'd reverse it:

>>> reversed_dict = dict((v, k) for k, v in dictionary.iteritems())
>>> print reversed_dict
{'1': 'T', '3': 'V', '2': 'U'}

Then you can loop through and just get them out:

>>> word = '12321'
>>> for character in word:
>>>     print reversed_dict[character]
T
U
V
U
T

If I've understood your question correctly...!

EDIT

Ok, so here's how this would work with yours:

dictionary = {'A':'&','B':'(','C':''}
reversed_dict = dict((v, k) for k, v in dictionary.iteritems())

word = '&('
new_word = ''
for letter in word:
    if letter in reversed_dict:
        new_word = new_word + reversed_dict[letter]
    else:
        new_word = new_word + letter
print new_word

Or, as suggested in the comments, a shorter version:

''.join(reversed_dict.get(letter, letter) for letter in word)
Ben
  • 6,687
  • 2
  • 33
  • 46
  • Thanks, but this isn't what i'm looking for. My thought might be i have to turn the dictionary into a list and then work with that? – Tiny Mar 11 '14 at 20:36
  • I'm afraid in that case I'm not 100% sure what you're after. Can you give expected input/output? – Ben Mar 11 '14 at 20:37
  • Ok... for example, i would like to iterate through each character in the phrase '&(*'. In my dictionary, i have defined dictionary = {'A':'&','B':'(','C','*'} Therefore, FOR EACH Character, i'm checking the dictionary so see if it corresponds to an existing 'VALUE' and, if it's in the dictionary, i will substitute the value for the key. In the example i've just given, &(* should be substituted for ABC. Hope this makes sense? It's kind of like a ciphertext program. – Tiny Mar 11 '14 at 20:43
  • Edited to show how you'd use it – Ben Mar 11 '14 at 20:52
  • I've never seen iteritems() before!!! I assume it iterates through each KEY:VALUE pair? – Tiny Mar 11 '14 at 20:53
  • @user3396486 Here you go! http://docs.python.org/2/library/stdtypes.html#dict.iteritems – Ben Mar 11 '14 at 20:57
  • `new_word = ''.join( reversed.get(letter, letter) for letter in word )` is much faster then iterating in a Python `for` loop and creating a new string object at each step with `+`. – chepner Mar 11 '14 at 21:29
  • Don't overwrite the builtin: `reversed`!!!!! – Russia Must Remove Putin Mar 11 '14 at 22:01
  • @AaronHall oops, well spotted ;) – Ben Mar 11 '14 at 22:41
1
def replace_chars(s, d):
    return ''.join(d.get(c, c) for c in s)

dictionary = {'T':'1','U':'2','V':'3'}
string = "SOME TEXT VECTOR UNICORN"
assert replace_chars(string, dictionary) == 'SOME 1EX1 3EC1OR 2NICORN'
pyrospade
  • 7,870
  • 4
  • 36
  • 52
0
>>> char_mappings = {'t': '1', 'u': '2', 'v': '3'}
>>> text = "turn around very slowly and don't make any sudden movements"
>>> for char, num in char_mappings.iteritems():
...     text = text.replace(char, num)
...
>>> print text
12rn aro2nd 3ery slowly and don'1 make any s2dden mo3emen1s
James Scholes
  • 7,686
  • 3
  • 19
  • 20
  • Interesting...have never seen .iteritems() function before? The original message is in ciphertext, so i suppose i swap the two parameters (char, num) around? The form of the message is like *"*$_ I then look up my dictionary to check if i have any symbols (like these) and if i do, i use the associated character (or the KEY in this case) Should work? – Tiny Mar 11 '14 at 20:51
0
#Okay lets do this
#your dictionary be:

dict = {'T':'1','U':'2','V':'3'}
#and let the string be:
str = "1do hello2 yes32 1243 for2"

new = ''
for letter in str:
    if letter in dict.values():
            new += dict.keys()[dict.values().index(letter)]
    else:
            new += letter

print new
nakkulable
  • 38
  • 4
  • I like this post...much simpler to understand. The line: dict.keys()[dict.values().index(letter)] I don't get the part after dict.keys()...surely Keys are not able to be indexed? (Runtime error: AttributeError: 'dict_values' object has no attribute 'index') – Tiny Mar 11 '14 at 21:27
  • Thanks. Sure you can. Check this post for better understanding. http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary – nakkulable Mar 11 '14 at 21:35
  • I don't understand what you are trying to do here. You are wrongly indexing the list and I don't even know why you need a list here at the first place. Please explain your problem clearly! – nakkulable Mar 11 '14 at 21:49
  • Your post has solved my problem anyhow. I simply needed to look up the associated KEY from a given VALUE in a dictionary. Thanks. – Tiny Mar 11 '14 at 22:05
  • @user3396486 If this answer was helpful please vote up! Thanks :) – nakkulable Mar 11 '14 at 22:07
  • Would wish so, but i can't. I need at least 15 reputation! – Tiny Mar 11 '14 at 22:57