map() function getting input

  • A+
Category:Languages

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.

Dict approach

d = dict() var = input('Enter input: ') key, value = var.split() d[key] = int(value) 

List approach

l = list() var = input('Enter input: ') key, value = var.split() l.append((key, int(value))) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: