Amen King
Amen King

Reputation: 37

how to create a dictionary from a list

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

Answers (3)

Nemanja Radojković
Nemanja Radojković

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:

  • enclosing the expression in {} tells it we are making a dictionary with this comprehension. x represents each member string within this comprehension
  • x.split() splits the string into a list of substrings, on "space" sign (by default, can be adjusted)

    • with [0] we grab the first substring ["@David,"]
    • with .strip(',@') we remove the comma and @ character around the name
    • with this we have created the dictionary key
  • Key value: int(x.split()[-1])

    • x.split()[-1] takes the last substring ('27')
    • enclosing it in int() we turn it into an integer

Upvotes: 1

jpp
jpp

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

Sufiyan Ghori
Sufiyan Ghori

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

Related Questions