简体   繁体   English

在两个字典中使用键值对(Python)

[英]Working with key-value pairs in two dictionaries (Python)

Say I have two dictionaries:假设我有两个字典:

score={"hello": 5, "goodbye": 1, "how are you": 7}
word_count = {"hello": 1, "goodbye": 1, "how are you": 3}

And an input:和一个输入:

text=input("Enter your text here: ")
text_list = text.split(" ")

And, if the key is in the input, I want to print the value.而且,如果键在输入中,我想打印该值。 How do I do this (using a for loop inside a for loop prints it twice)?我该怎么做(在 for 循环中使用 for 循环会打印两次)? My output looks like this:我的输出如下所示:

for sentence, rating in score:
   for sent, rate in word_count:
       number = int(rating) / (int(rate) - len(text_list))
       print(number)

if the dictionaries are same length you can loop for one dic如果字典的长度相同,则可以循环查找一个 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

Assuming the keys in score and word_count are the same.假设 score 和 word_count 中的键相同。

If the key is in the input, print the value :如果键在输入中,则打印值:

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}')

input :输入 :
hello how are you I am fine goodbye

output :输出 :

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM