map() function getting input
Solution 1
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)))
Solution 2
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.')
Solution 3
You need to split the input and save it to a dictionary.
data = dict()
keyValue = input()
data[keyValue.split(' ')[0]) = keyValue.split(' ')[1]
Solution 4
usr_inpt = input("enter whatever you want to enter: ")
id, value = usr_inpt.split()
output = [(id,value)]
this formats your input into a tuple
...but I would not recommend dictionary
, since every key must be unique and if you have multiple entries from the user, you could end up overwriting previously inputted user inputs.
Solution 5
>>> i = "id"
>>> x = 1234
>>> out = {i:x}
>>> out
{'id': 1234}
>>> out = [(i,x)]
>>> out
[('id', 1234)]
>>>
>>>
>>>
>>> ix = input("--> ")
--> id 1234
>>> ix = ix.split()
>>> out = {ix[0]:int(ix[1])}
>>> out
{'id': 1234}
>>> out = [(ix[0],int(ix[1]))]
>>> out
[('id', 1234)]
>>>
Or maybe a function will work:
>>> add = lambda x:{x.split()[0],int(x.split()[1])}
>>> out = add(input("--> "))
--> id 1234
>>> out
{1234, 'id'}
>>>
FrastoFresto
Updated on July 05, 2022Comments
-
FrastoFresto almost 2 years
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
-
chepner over 5 yearsNote that this ignores whatever handling you need to provide in case the user doesn't provide the expected input.
-
chepner over 5 years
input
always returns astr
; you don't need to callstr
yourself. -
FrastoFresto over 5 years@jpp thank you very much,but I was curious to know can the code you wrote be compressed in a map()?
-
chepner over 5 years@FarzinNasiri No!
map
applies the same function to every element in an iterable; you don't want to do that. -
Cut7er over 5 yearsthanks for the clarification - mostly I do
int(input())
for numbers, didnt occured to me that it is not needed for string input :-) -
Thijs van Ede over 5 years@schwobaseggl you're completely right, I edited it in my answer
-
jpp over 5 years@FarzinNasiri, I've also added some error-handling to ensure the correct format is supplied.
-
SethMMorton over 5 years
split()
should be preferred oversplit(‘ ‘)
since it with split on an arbitrary number of white space characters, as well as handle tabs.