[英]Working with key-value pairs in two dictionaries (Python)
假設我有兩個字典:
score={"hello": 5, "goodbye": 1, "how are you": 7}
word_count = {"hello": 1, "goodbye": 1, "how are you": 3}
和一個輸入:
text=input("Enter your text here: ")
text_list = text.split(" ")
而且,如果鍵在輸入中,我想打印該值。 我該怎么做(在 for 循環中使用 for 循環會打印兩次)? 我的輸出如下所示:
for sentence, rating in score:
for sent, rate in word_count:
number = int(rating) / (int(rate) - len(text_list))
print(number)
如果字典的長度相同,則可以循環查找一個 dic
score = {"hello": 5, "goodbye": 1, "how are you": 7}
word_count = {"hello": 1, "goodbye": 1, "how are you": 3}
text = input("Enter your text here: ")
if text in score:
score[text] # do whatever with it
word_count[text] # do whatever with it
假設 score 和 word_count 中的鍵相同。
如果鍵在輸入中,則打印值:
score = {"hello": 5, "goodbye": 1, "how are you": 7}
word_count = {"hello": 1, "goodbye": 1, "how are you": 3}
input_text = input("Enter your text here: ")
size = len(input_text.split(" "))
for key in score:
if key in input_text:
rating = score[key]
rate = word_count[key]
print(f'{key:<12} : {rating / rate - size:.2f}')
輸入 :
hello how are you I am fine goodbye
輸出 :
hello : -3.00 # 5 / 1 - 8
goodbye : -7.00 # 1 / 1 - 8
how are you : -5.67 # 7 / 3 - 8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.