[英]Converting this list into Dictionary using Python
list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
我希望这个列表在一个字典中,键作为Name
, country
, game
和值,如Sachin
, India
, cricket
作为相应的值。 我使用文本文件中的readlines()
获取此列表。
>>> 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'}
只是使用正则表达式的另一种方式。
>>> lis = ['Name=Sachin\n','country=India\n','game=cricket\n']
>>> dict(re.findall(r'(\w+)=(\w+)',''.join(lis)))
{'Name': 'Sachin', 'game': 'cricket', 'country': 'India'}
在一行:
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'}
注意: list
ist不是一个好的变量名!
strip()
被调用两次,这不是很好 - 这可能更好:
def splt(item):
sp = item.strip().split('=')
return sp[0], sp[1]
dct = dict( splt(item) for item in lst )
print(dct)
以下应该有效:
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
这会给你以下字典:
{'country': 'India', 'game': 'cricket', 'Name': 'Sachin'}
注意,您不应该使用list
的变量名,因为它用作Python函数。
如果您正在读取文件,则可以执行以下操作:
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
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()
使用字典理解:
d = {
k: v
for k, v in map(
lambda x: x.strip().split('='),
yourlist
)
}
正如彼得伍德建议重命名你的列表变量而不是遮蔽内置list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.