Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting this list into Dictionary using Python

Tags:

python

list

list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']

I want this list in a dictionary with keys as Name, country, game and values as Sachin, India, cricket as corresponding values. I got this list using readlines() from a text file.

like image 930
Abhishek Raj Avatar asked Dec 03 '22 16:12

Abhishek Raj


2 Answers

>>> lst = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
>>> result = dict(e.strip().split('=') for e in lst)
>>> print(result)
{'Name': 'Sachin', 'country': 'India', 'game': 'cricket'}
like image 125
Ozgur Vatansever Avatar answered Dec 05 '22 07:12

Ozgur Vatansever


Just another way using regex.

>>> lis = ['Name=Sachin\n','country=India\n','game=cricket\n']
>>> dict(re.findall(r'(\w+)=(\w+)',''.join(lis)))
{'Name': 'Sachin', 'game': 'cricket', 'country': 'India'}
like image 32
Avinash Raj Avatar answered Dec 05 '22 05:12

Avinash Raj