Python 如何从文件中每行的第三个单词生成字典条目

Python 如何从文件中每行的第三个单词生成字典条目,python,dictionary,key,key-value,Python,Dictionary,Key,Key Value,我有一个文本文件: hey student1 aaa 123 yes hi student2 bbb 321 yes hello student3 aaa 432 no hi student4 bbb 589 yes 我想在python中使用字典数据结构将所有带有aaa的行分组在一起,并发送到一个名为aaa_file的文件,然后对bbb执行相同的操作 我试过的代码: import json import sys with open("text.txt", 'r') as f: line

我有一个文本文件:

hey student1 aaa 123 yes
hi student2 bbb 321 yes
hello student3 aaa 432 no
hi student4 bbb 589 yes
我想在python中使用字典数据结构将所有带有aaa的行分组在一起,并发送到一个名为aaa_file的文件,然后对bbb执行相同的操作

我试过的代码:

import json
import sys

with open("text.txt", 'r') as f:
   lines = f.readlines

newDict{}

for line in lines    
    unit = line.split()    
    newDict[unit[2]]=unit[0:]
print(json.dumps(newDict, indent = 4))

此代码将帮助您实现这一点

import json
import sys
from collections import defaultdict

with open("text.txt", 'r') as f:
   lines = f.readlines()[1:]

newDict = defaultdict(list)

for line in lines:
    print(line)
    unit = line.split(" ")
    newDict[unit[2]].append(unit)
print(json.dumps(newDict, indent = 4))
for key in newDict:    
    with open("{}_list.json".format(key), "w") as f:
        for i in newDict[key]:
            f.write(" ".join(i) + "\n")
输出

   {
    "aaa": [
        [
            "hey",
            "student1",
            "aaa",
            "123",
            "yes"
        ],
        [
            "hello",
            "student3",
            "aaa",
            "432",
            "no"
        ]
    ],
    "bbb": [
        [
            "hi",
            "student2",
            "bbb",
            "321",
            "yes"
        ],
        [
            "hi",
            "student4",
            "bbb",
            "589",
            "yes"
        ]
    ]
}

请用您尝试过的代码更新您的问题。评论不用于扩展讨论;这段对话已经结束。