Reputation: 37
I have a list of sentence and I want to convert it into a diction only include the username and the age.
list=['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']
The output I want to get is a dictionary like
dic={David:27,John:99,rain:45}
Thanks for the help
Upvotes: 1
Views: 69
Reputation: 189
Try a dict comprehension:
dic = {x.split()[0].strip(',@'): int(x.split()[-1]) for x in member_list}
If you need clarification on the parts of the expression, please tell.
EDIT: Clarification, as required:
Ok, so:
{}
tells it we are making a dictionary with this comprehension. x represents each member string within this comprehensionx.split()
splits the string into a list of substrings, on "space" sign (by default, can be adjusted)
[0]
we grab the first substring ["@David,"].strip(',@')
we remove the comma and @ character around the nameKey value: int(x.split()[-1])
x.split()[-1]
takes the last substring ('27')int()
we turn it into an integerUpvotes: 1
Reputation: 164623
You can define a custom function, apply it to each string via map
, then feed to dict
:
L = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']
def key_value_extractor(x):
x_split = x.split(',') # split by ','
name = x_split[0][1:] # take 1st split and exclude first character
age = int(x_split[1].rsplit(maxsplit=1)[-1]) # take 2nd, right-split, convert to int
return name, age
res = dict(map(key_value_extractor, L))
{'David': 27, 'John': 99, 'rain': 45}
Upvotes: 2
Reputation: 18743
You can use dictionary comprehension
l = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']
X = {item.split(',')[0][1:]:int(item.split(',')[1].rsplit(maxsplit=1)[-1]) for item in l}
print(X)
#output
{'David': 27, 'John': 99, 'rain': 45}
Upvotes: 0