[英]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.