[英]Converting a text file to python dictionary - one key and multiple values - with exclusion of one field
我有以下制表符分隔的文本文件:
1 John 27 doctor Chicago
2 Nick 33 engineer Washington
我正在尝试将其转换为python字典,其中的关键字是NAME,年龄,职业和地址是值。 我想排除排名(1、2)。
码:
myfile = open ("filename", "r")
d = { }
for line in myfile:
x = line.strip().split("\t")
key, values = int(x[0]), x[1:]
d.setdefault(key, []).extend(values)
print(d)
您可以将其转换为按名称索引的dict,而不是元组中的值:
d = {}
with open('filename', 'r') as myfile:
for line in myfile:
_, name, *values = line.strip().split("\t")
d[name] = values
print(d)
使用您的样本输入,将输出:
{'John': ('27', 'doctor', 'Chicago'), 'Nick': ('33', 'engineer', 'Washington')}
您无需解释面临的困难。 但是,从制表符分隔的文本示例中,您希望具有以下类似的字典:
{'John': ['27', 'doctor', 'Chicago'], 'Nick': ['33', 'engineer', 'Washington']}
如果这是您想要达到的输出,那么我对您的代码进行了一些修改。
myfile = open ("filename", "r")
d = { }
for line in myfile:
x = line.strip().split("\t")
key, values = x[1], x[2:]
d.setdefault(key, []).extend(values)
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.