I'be trying to get an special input from the user and then save it in something like a dictionary. The input I have in mind is something like:
>>> id 1230
and I want it to be save in the form of:
{"id":1230}
or
[(id,1230)]
my problem is that there are actually two variables,one is a string and another is an integer,so somehow I have the get a line from the user,then the first and second parts should be separated and saved in one of the forms I mentioned. I know it has to do with the map() function and maybe a lambda expression is also used.once I used such a code to get two integers:
x,y = map(int,input().split())
but I really don't know how to do it with a string and integer. Thank you very much
The question about whether you would like to store the data as a dict
or a list of tuples
depends on whether you want the user to overwrite existing values or not. If you store the values in a dict
, the input of
id 1230
hi 16
id 99
will produce a dictionary like {"id": 99, "hi":16}
because the second input id
overwrites the first. A list of tuples approach would produce [("id", 1230), ("hi", 16), ("id", 90)]
.
How to parse the values has already been suggested by other people, but for completion I will add it to my answer as well.
d = dict()
var = input('Enter input: ')
key, value = var.split()
d[key] = int(value)
L = list()
var = input('Enter input: ')
key, value = var.split()
L.append((key, int(value)))
You do not need map
here. You can use str.split
to split by whitespace and then create a dictionary explicitly:
var = input('Enter input: ') # 'id 1230'
key, value = var.split()
d = {key: int(value)} # {'id': 1230}
You can add some checks to ensure the format is input correctly before proceeding with creating the dictionary:
while True:
try:
var = input('Enter input: ') # 'id 1230'
key, value = var.split()
d = {key: int(value)} # {'id': 1230}
break
except ValueError:
print('Incorrect format supplied, type "id 1230" expected. Please try again.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With