[英]File, strip each line and add to key in dictionary
How do we split the first line in a text file and make them as keys, and every line after that are the values for each key. 我们如何分割文本文件中的第一行并将其作为键,之后的每一行都是每个键的值。 Without any imports 没有任何进口
What I have so far: 到目前为止,我有:
new_dict = {}
with open(file, 'r') as f:
for line in f:
list = line.strip().split(',')
for item in list:
new_dict[item] = []
what this outputs: {'name': [], 'last': [], 'middle': []}
输出的内容: {'name': [], 'last': [], 'middle': []}
Now, how do I move on to the next line, split at the comma and append the first element to the first key, the second element to the second key, etc. 现在,我如何继续下一行,在逗号处分割并将第一个元素附加到第一个键,将第二个元素附加到第二个键,依此类推。
file:
name, last, middle
bob, jones, m
jones, bob, k
alice, lol, f
Result in the end: 最终结果:
{'name': ['bob', 'jones', 'alice'], 'last': ['jones', 'bob', 'lol'], 'middle': ['m', 'k', 'f']}
new_dict = {}
names = [] # used map 0, 1, 2 to `name`, `last`, `middle`
with open('/path/to/test.txt') as f:
# Handle header (the first) line: `name, last, middle`
for name in next(f).split(','): # split fields by `,`
name = name.strip() # remove surrounding spaces
names.append(name)
new_dict[name] = [] # initialize dictionary with empty list.
# Handle body.
for line in f:
# enumerate(['bob', 'jones', 'm']) return an interator
# that generates (0, 'bob'), (1, 'jones'), (2, 'm')
for i, value in enumerate(line.split(',')):
new_dict[names[i]].append(value.strip())
print(new_dict)
output: 输出:
{'middle': ['m', 'k', 'f'], 'last': ['jones', 'bob', 'lol'], 'name': ['bob', 'jones', 'alice']}
answer = {}
for attr in "name last middle".split():
answer[attr] = []
with open("path/to/input") as infile:
for line in infile:
for k,v in zip("name last middle".split(), line.strip().split(',')):
answer[k].append(v)
I guess the logic is: 我猜逻辑是:
,
. 阅读的第一行,把它分解上,
。 Here is an approach for the above logic: 这是上述逻辑的一种方法:
d = {}
with open('somefile.txt') as f:
first_line = next(f)
for column_title in first_line.split(','):
d[column_title.strip()] = []
for line in f:
if line.strip():
# this will skip blanks
name, last, middle = line.split(',')
d['name'].append(name.strip())
d['last'].append(last.strip())
d['middle'].append(middle.strip())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.