2016-03-31 35 views
1

我正在寫密碼,並且已將數字值分配給字母表中的每個字母alphabet_dictionary = {'a': 0, 'b': 1, 'c': 2,... etc.}如何使用python 3字典中的值查找密鑰?

我首先將message中的字母轉換爲數字,進行一些算術運算並將這些數字存儲在名爲code的變量中。

我想將它們轉換回字母。

到目前爲止,我有:

for number in code: 
    for letter, value in alphabet_dictionary.items(): 
     if value == number: 
      coded_message.append(letter) 

這工作。我的coded_message列表中有一個正確的編碼信息。有更好或更有效的東西嗎?

爲什麼我不能在一行中做到這一點?我第一次嘗試使用:

for number in code: 
    coded_message.append(letter for letter, value in alphabet_dictionary.items() if value == number) 

但只追加內存分配地址,例如單個字符:

`[<generator object <genexpr> at 0x1011bb240>, <generator object <genexpr> at 0x1011bb1f8>, <generator object <genexpr> at 0x1011bb288>, <generator object <genexpr> at 0x1011bb2d0>, <generator object <genexpr> at 0x1011bb318>, <generator object <genexpr> at 0x1011bb360>, <generator object <genexpr> at 0x1011bb3a8>]' 

這究竟是爲什麼?

+1

[逆字典查找 - 的Python]的可能的複製(http://stackoverflow.com/questions/25 68673/inverse-dictionary-lookup-python) –

+0

如果你完全確定只有一個匹配的值可以使用'coded_message。append(下一個(字母的字母,值爲alphabet_dictionary.items(),如果value == number))'獲得生成器表達式的下一個(第一個)值,但是作爲[反向字典查找 - Python]的接受答案(http ://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python)指出:沒有繼承保證該值存在於字典中。 –

+0

由於您只是簡單地將字母鏈接到數字,您可以使用'string.ascii_lowercase [index]'通過索引和'string.ascii_lowercase.index(char)'查找字母以獲取字符的索引。 –

回答

1

您沒有獲得letter的內存位置,您正在獲取它認爲是您(無意)創建的生成器的內存位置。 .append()只有一個參數,當你給它一個generator-expr時,它很樂意將它作爲參數,並添加它。您可以包住GEN-EXPR在next作爲@Tadhg麥當勞 - 延森提到,或者你可以嘗試改變.append().extend()

要詳細一點:

x = letter for letter, value in alphabet_dictionary.items() if value == number 
type(x) ## generator-expression 
for i in x: 
    print(i) 
## will only print the single value that satisfied this generator 

同樣,如果你來了一個明確的在.append()內部列表理解,它可能會更容易顯示問題:

for number in code: 
    coded_message.append([letter for letter, value in alphabet_dictionary.items() if value == number]) 

coded_message 
## [["a"], ["b"],... ] - not the right order, of course, but now you have a list of lists, which is probably not what you want. 

如果您使用nextextend,你會得到一個列表信件,這可能是你想要的。

儘管如此,如果你想要反向映射,我也會建立反向映射作爲字典。當你第一次創建你的映射例如「a」= 0時,也可以創建一個0 =「a」的字典。這將是查找(以字母大小的列表,你可能永遠也不會注意到雖然)更快,並且可以讓你做到健全檢查,如

for letter, number in alphabet_dict.items(): 
    if number_dict[number] != letter: 
     raise "Something got confused: got {}->{}->{}".format(letter, number, number_dict[number]) 
0
import string 
#this builds a similar dictionary to yours: 
alphabet_dictionary = {a:ord(a)-ord('a') for a in string.ascii_lowercase} 

您可以使用map

code = 'somestring' 
coded_message = map(alphabet_dictionary.__getitem__, code) 

對於解碼:

#invert the dictionary, in your case it's easy because it's 1-to-1: 
decode_dictionary = {v:k for k,v in alphabet_dictionary.items()} 
decoded_message = map(decode_dictionary.__getitem__, coded_message) 
相關問題