简体   繁体   English

归档,去除每一行并添加到字典中的键

[英]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: 我猜逻辑是:

  1. Read the first line, split it on , . 阅读的第一行,把它分解上,
  2. Take each value and create the keys of a dictionary. 取每个值并创建字典的键。
  3. Read the rest of the lines and add them to a list corresponding to the correct 'column' or key. 阅读其余的行,并将它们添加到与正确的“列”或键对应的列表中。

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.

相关问题 如何通过读取.txt文件的每一行来将键值添加到字典中并更新值? - How can I add key values into a dictionary from reading in each line of a .txt file and update values? Python:如何拆分文件中的每一行代码并添加到字典中 - Python: How to Split Each Line of Code in a File and Add to a Dictionary 转换为字典的多行字符串已\r\n附加到字典中的键,如何去除\r\n? - Multi-line string on converting to dictionary has \r\n appended to key in dictionary, how to strip \r\n? 使用键和值将文件添加到字典 - Add a file to dictionary with key and values 如何从文本文件的每一行中删除一段文本? - How to strip a certain piece of text from each line of a text file? Python:在每个字典键上添加一个子列表 - Python: add a sublist on each dictionary key 从文件中创建字典,第一个单词是每行的关键,然后其他四个数字将成为元组值 - Making a dictionary from file, first word is key in each line then other four numbers are to be a tuple value 如何将 python 字典的每个键值对存储在 json 文件中的单独行上? - How can I store each key-value pair of my python dictionary on a separate line in json file? 如何使用每个新段落的第一行中的键从按段落分隔的文本文件在python中制作字典? - How to make a dictionary in python from a text file seperated by paragraph with the key in the first line of each new paragraph? 读取具有键值对的文本文件,并使用python pandas将每一行转换为一个字典 - read a text file which has key value pairs and convert each line as one dictionary using python pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM