简体   繁体   中英

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)? 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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