'How can I make a function called build() have one string input and it returns a dictionary?
I have a project that requires me to make a function that takes a string input and return a dictionary.
The string will be consist of a name and a phone number, separated by a comma.
Example of the input: Joe,123-5432 Joe Example of the output: 123-5432
Solution 1:[1]
def take_input(x):
dict={}
mylist=x.split(',',maxsplit=2)
dict[mylist[0]]=mylist[1]
#dict['name']=mylist[0]
#dict['phone']=mylist[1] output={'name:'Jeo','phone':'123-5432'
return dict
x=' Joe,123-5432'
print(take_input(x))
output=
{' Joe': '123-5432'}
Solution 2:[2]
Please take a look at this:
# Function to split a user provided string and delimiter
# And convert it in to a dictionary
def str_to_dict(_user_input_string, _user_provided_delimiter):
return {_user_input_string.split(_user_provided_delimiter)[0]: _user_input_string.split(_user_provided_delimiter)[-1]}
x = str_to_dict('Joe,123-5432', ',')
print(x, type(x))
#Output
{'Joe': '123-5432'} <class 'dict'>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zeeshan12396 |
| Solution 2 | Ashish Samarth |
