Home > Enterprise >  I would like to divide it into command, key, and value through input split and enter it in the dicti
I would like to divide it into command, key, and value through input split and enter it in the dicti

Time:10-31

database = {}

while True:
    print("Pleas type like Command,textA,textB")

    Command, textA, textB = input().split(',')

    if Command == 'PUT': // ex: PUT,a,c  PUT is command to a is key, c is value
        database[textA] = textB
        print("Success!")
    elif Command == 'GET': // ex: GET,a GET is command to get a's value
        if "textA" in database:
            print(database.get('textA'))
        else:
            print("Not exist!")
    elif Command == 'DELETE': // ex: DELETE,a DELETE is command to delete a's key&value
        if "textA" in database:
            del database['textA']
            print("Success!")
        else:
            print("Not exist!")
    elif Command == 'LIST':
        if "textA" in database:
            for KEY, VALUE in database.items():
                print(KEY, VALUE)
        else:
            print("Not exist!")

I would like to receive a command and key value in the dictionary and operate the if statement according to each command. However, if statement works only when three values are received unconditionally, so GET, DELETE, and LIST cannot be used. I'm trying to use TRY and EXCEPT, but I don't understand well. Also, if you enter textA and textB exactly like that, I wonder if Key and Value will continue to be stored in the Dictionary Database. There are many restrictions because the input format is Command, textA, and textB unconditionally. I think I have to organize it with a repeat sentence, but I wonder if there is another way.

CodePudding user response:

I think you are a python beginner, because some things went wrong in your code as i understand your intentions:

  1. To comment Text use #, not //
  2. To use a variable name them directly, do not use quotes, quotes are for strings
  3. You should use lowercase variable names with underscores (PEP Styleguide)

To fix you problem of splitting, you can use a list to hold your data and than pop the items from list and use try catch block that catches only the IndexError

database = {}

while True:
    print("Pleas type like Command,textA,textB")

    in_data = input().split(',')    # Save into list
    Command = in_data.pop(0)        # Take 1 element
    textA = in_data.pop(0)          # Take 1 element
    try:
        textB = in_data.pop(0)      # Take 1 element ..
    except IndexError:              # .. if available
        textB = None

    if Command == 'PUT':  # ex: PUT,a,c  PUT is command to a is key, c is value
        database[textA] = textB
        print("Success!")
    elif Command == 'GET':  # ex: GET,a GET is command to get a's value
        if textA in database:
            print(database.get(textA))
        else:
            print("Not exist!")
    elif Command == 'DELETE':  # ex: DELETE,a DELETE is command to delete a's key&value
        if textA in database:
            del database[textA]
            print("Success!")
        else:
            print("Not exist!")
    elif Command == 'LIST':
        if textA in database:
            for KEY, VALUE in database.items():
                print(KEY, VALUE)
        else:
            print("Not exist!")

Additonaly you should check your input (e.g. has it the correct type), to be more safe and you can define a default value for dict.get (print(database.get(textA, "Not exist!")))

CodePudding user response:

You can pad the split text with extra empty strings so that the unpacking always works:

Command, textA, textB, *_ = input().split(',') ['','']

CodePudding user response:

Try this:

from itertools import zip_longest

text = input().split(',')
Command, textA, textB = dict(zip_longest(range(3),text)).values()

or this:

from itertools import zip_longest
from types import SimpleNamespace

text = input().split(',')
params = SimpleNamespace(**dict(zip_longest(['Command', 'textA', 'textB'],text)))

# test
print(params.Command)
print(params.textA)
print(params.textB)
  • Related