Caroline.py
Caroline.py

Reputation: 313

Getting user input in a certain format (Python 3.5)

I have used a .CSV file to create my code, but now I want to replace the .CSV file and ask the user for input. My .CSV file has two columns: 1) make and 2) sold, where make are different vehicle makes and sold has the number of makes of vehicles sold in 2014. This .CSV file has been converted to a dictionary.

My question is, how can I ask the user for data so that I can make a similar dictionary (make and sold)? I tried asking a series of if and else statements asking for this input, but there has to be a more elegant way to manage a large set of data.

Reading in my files gives (just using three makes as an example):

{'Jeep': 1017019, 'Ford': 2480942, 'BMW': 1811719}

I want to create a similar dictionary, but just by asking the user for their input.

Upvotes: 0

Views: 32

Answers (2)

McGrady
McGrady

Reputation: 11477

You can try to use split() to get the key value and generate the dict:

d={}
while True:
    _input_ = raw_input()
    if _input_:
        try:
            d[_input_.split()[0]]=int(_input_.split()[1])
        except Exception as e:
            print e
    else:
        break
print d

Jeep 1
BMW 2
Ford 3

{'Jeep': 1, 'BMW': 2, 'Ford': 3}

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

Essentially, you need a loop. Since you can't know ahead of time how many iterations, using a while loop would be appropriate. Use try-except to validate the input, and use a sentinel value to let the user break out of the loop.

In [51]: data = {}
    ...: while True:
    ...:     inpt = input("Enter data seperated by a space, or 'done' when finished\n")
    ...:     try:
    ...:         k, v = inpt.split()
    ...:     except ValueError:
    ...:         if inpt.strip() == 'done':
    ...:             break
    ...:         print("Invalid input, please try again")
    ...:     else:
    ...:         data[k] = v
    ...:
Enter data seperated by a space, or 'done' when finished
Jeep 10170
Enter data seperated by a space, or 'done' when finished
Ford 12321
Enter data seperated by a space, or 'done' when finished
BMW10202
Invalid input, please try again
Enter data seperated by a space, or 'done' when finished
BMW 1020
Enter data seperated by a space, or 'done' when finished
done

In [52]: data
Out[52]: {'BMW': '1020', 'Ford': '12321', 'Jeep': '10170'}

Upvotes: 1

Related Questions