Reputation: 51
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.
Upvotes: 4
Views: 123
Reputation: 7428
Use dictionary comprehension:
d = {
k: v
for k, v in map(
lambda x: x.strip().split('='),
yourlist
)
}
And as Peter Wood suggested rename your list variable not to shadow the built-in list
.
Upvotes: 0
Reputation: 52153
>>> 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'}
Upvotes: 10
Reputation: 46759
The following should work:
my_list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
my_dict = {}
for entry in my_list:
key, value = entry.strip().split('=')
my_dict[key] = value
print my_dict
This give you the following dictionary:
{'country': 'India', 'game': 'cricket', 'Name': 'Sachin'}
Note, you should not use a variable name of list
as this is used as a Python function.
If you are reading from a file, you could do this is follows:
with open('input.txt', 'r') as f_input:
my_dict = {}
for entry in f_input:
key, value = entry.strip().split('=')
my_dict[key] = value
print my_dict
Upvotes: 1
Reputation: 113965
answer = {}
with open('path/to/file') as infile:
for line in infile: # note: you don't need to call readlines()
key, value = line.split('=')
answer[key.strip()] = value.strip()
Upvotes: 0
Reputation: 174706
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'}
Upvotes: 4
Reputation: 46859
in one line:
lst =['Name=Sachin\n','country=India\n','game=cricket\n']
dct = dict( (item.split('=')[0], item.split('=')[1].strip()) for item in lst )
print(dct)
# {'game': 'cricket', 'country': 'India', 'Name': 'Sachin'}
note: list
ist not a good variable name!
strip()
is called twice which is not all that nice - this may be better:
def splt(item):
sp = item.strip().split('=')
return sp[0], sp[1]
dct = dict( splt(item) for item in lst )
print(dct)
Upvotes: 2