這裏有一個奇怪的位,儘管我確信我正在做一些愚蠢的事情,而剛剛轉換爲Python。我有一個dict
的dict
一個dict
(我知道誰家不會喜歡),其代碼如下:字典不區分大小寫,但不知道爲什麼
import sys
hash = {}
def update_official():
for keyv in hash:
for word in hash[keyv]:
if word == 'Alice':
hash[keyv][word]["official"] = 1
else:
hash[keyv][word]["official"] = 0
def add_case_terms():
new_terms = {}
for term_id in hash:
for term in dict[term_id]:
if term_id not in new_terms:
new_terms[term_id] = {}
new_terms[term_id][term.title()] = hash[term_id][term]
new_terms[term_id][term.upper()] = hash[term_id][term]
new_terms[term_id][term.lower()] = hash[term_id][term]
for term_id in new_terms:
for term in new_terms[term_id]:
hash[term_id][term] = new_terms[term_id][term]
def main():
key1 = 1
words = ['Alice','John']
for word in words:
if key1 not in dict:
hash[key1] = {}
hash[key1][word] = {"official":0,"other_info":5}
add_case_terms()
update_official()
for key in hash:
for term in hash[key]:
print str(term) + " has official: " + str(hash[key][term]["official"])
print "\nAmending 'alice'.\n"
hash[1]['alice']["official"] = 1
for key in hash:
for term in hash[key]:
print str(term) + " has official: " + str(hash[key][term]["official"])
if __name__ == "__main__":
sys.exit(main())
我得到的輸出是:
john has official: 0
Alice has official: 0
ALICE has official: 0
John has official: 0
JOHN has official: 0
alice has official: 0
Amending 'alice'.
john has official: 0
Alice has official: 1
ALICE has official: 1
John has official: 0
JOHN has official: 0
alice has official: 1
我不要什麼」不明白爲什麼每個alice
鍵得到更新,而不僅僅是對應於正確的情況。有任何想法嗎?
命名你的詞典'詞典'是一個壞的舉動,因爲它影響內置。 – jonrsharpe 2014-11-14 13:46:43
你可以顯示一些輸出。如果我必須猜測它不是這個詞典不區分大小寫,而是與你調用term.upper()和term有關。lower() – user2097159 2014-11-14 13:48:03
你更新'main'中的'dict [1] ['alice']',並在'update_official'中更新'word =='Alice''的情況 - 爲什麼你會對輸出感到驚訝? – jonrsharpe 2014-11-14 13:48:51