2

I'm new to python while loop and dictionary.

I want to write a code sample that prompts repeatedly prompts the user for a key followed by a value. The key and value should then be stored in a dictionary.

It should stop prompting the user for keys and values once the user enters the word "Done" as a key followed by "Done" as a value. We may assume that the user will only enter string-type keys and string-type values. We also do not need to worry about duplicate keys.

After the user types "Done" for value and "Done" for key, the code sample should then prompt the user for one lookup key. It will print out the value of that key and finish.

See below for examples...

Example

Key: Tu

Value: Tuesday

Key: We

Value: Wednesday

Key: Th

Value: Thursday

Key: Fr

Value: Done

Key: Sa

Value: Saturday

Key: Done

Value: Done

What would you like to look up? Fr

Done

My codes (how to fix it?):

a = input('Key: ')
b = input('Value: ')
dict = {a: b}
while a != 'Done' and b != 'Done':
        new_dict = {input('Key: '): input('Value: ')}
        dict.update(new_dict)
key = input('What would you like to look up?')
print(dict.get(key))

4 Answers 4

3

I think you need:

d = {}
while True:
    k = input("key: ")
    v = input("value: ")
    d[k] = v
    if k=="Done" and v=="Done":
        break

x = input("What would you like to look up?")

print(d.get(x))
Sign up to request clarification or add additional context in comments.

Comments

2

There are several things to fix:

  • Define dictionary:

    d = dict() OR d = {}
    
  • Set key and value:

    d[a] = b
    
  • I'm not sure why would you need another while nested loop.

Anyway, here is an example of how you can implement the above definitions:

d = dict()
a = raw_input('Key: ')
b = raw_input('Value: ')
d[a] = b
while a != 'Done' and b != 'Done':
    a = raw_input('Key: ')
    b = raw_input('Value: ')
    d[a] = b

for k, v in d.iteritems():
    print k+":  " + v

Comments

2

You can use get as the condition for the while loop:

d = {}
while d.get('Done','') != 'Done':
    key = input('Key: ')
    val = input('Val: ')
    d[key] = val
print(d.get(input("What would you like to look up?:"),"Not present in Dict"))
print("Done")

Sample run:

Key: Mo

Val: Monday

Key: Tue

Val: Tuesday

Key: Done

Val: Done

What would you like to look up?:Mo
Monday
Done

Comments

0

You may use this code-

dict1 = {}
while True:
    a = input('Key: ')
    b = input('Value: ')
    dict1[a] = b
    if a == b == "Done":
        break
key = input('What would you like to look up?\n')
print(dict1[key])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.