Python Dictionary: Get associated 'Key' from 'Value'?
本问题已经有最佳答案,请猛点这里访问。
我建立了一个简单的形式字典:
1 | dictionary = {'T':'1','U':'2','V':'3') |
我要做的是迭代一条消息,并使用下面的代码,用一个关联的键值交换一个数字的每个实例。
1 2 3 | for character in line: if character in dictionary and character.isalpha() !=True: equivalent_letter = dictionary(key??) |
号
有什么想法吗?
如果您经常使用反向映射,我会将其反向:
1 2 3 | >>> reversed_dict = dict((v, k) for k, v in dictionary.iteritems()) >>> print reversed_dict {'1': 'T', '3': 'V', '2': 'U'} |
然后你可以通过循环把它们拿出来:
1 2 3 4 5 6 7 8 | >>> word = '12321' >>> for character in word: >>> print reversed_dict[character] T U V U T |
号
如果我正确理解了你的问题…!
编辑
好吧,下面是你的方法:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
或者,正如评论中所建议的,一个较短的版本:
1 | ''.join(reversed_dict.get(letter, letter) for letter in word) |
。
1 2 3 4 5 6 | 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' |
。
1 2 3 4 5 6 7 | >>> 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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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 |
。