Python词典:获取关联的'密钥'来自'价值'?

时间:2014-03-11 20:29:32

标签: python dictionary

我已经设置了一个简单的表格字典:

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

我要做的是迭代一条消息并使用以下代码,用关联的键值交换数字的每个实例。

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

有什么想法吗?

4 个答案:

答案 0 :(得分:3)

如果您经常反向使用映射,我会反过来:

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

然后你可以循环并将它们拿出来:

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

如果我能正确理解你的问题......!

修改

好的,所以这是如何与你合作的:

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

或者,正如评论中所建议的那样,更短的版本:

''.join(reversed_dict.get(letter, letter) for letter in word)

答案 1 :(得分: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'

答案 2 :(得分: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

答案 3 :(得分:-1)

#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