从单个列表创建列表字典?

Creating a dictionary of lists from a single list?

我有一个关于听写的问题。我是一个菜鸟,一直在广泛地研究这个话题,但我似乎无法全神贯注。我想做的是从一个文本文件(1200 万个术语)中获取这个巨大的列表,将其放入字典中,然后将具有某些共同特征的项目放入字典中的一个列表中,这样当我搜索时字典,显示具有该特征的每个元素。

一些列表元素的示例:

0022 hello https:example.com/blah

0122 john https:example.com/blah

3502 hello https:example.com/blah

现在根据上面的数据,我想要一个 dict 元素,它是每次出现单词 "hello" 并且以 "hello" 作为键的列表,所以当我搜索"hello" 我会 return

0022 hello https:example.com/blah

3502 hello https:example.com/blah

关于如何高效执行此操作的任何提示?

我知道数据库可能是一个更快更好的解决方案,但我对数据库一无所知,我什至不是 CS 学生我只是在选修。感谢您的帮助

按照建议,defaultdict(list) 非常适合这样做:

from collections import defaultdict

data = defaultdict(list)

with open('input.txt') as f_input:
    for line in f_input:
        key = line.split()[1]
        data[key].append(line)

print(''.join(data['hello']))

这将显示以下行:

0022 hello https:example.com/blah
3502 hello https:example.com/blah

这是一个pandas解决方案:

import pandas as pd

lst = ['0022 hello https:example.com/blah',
       '0122 john https:example.com/blah',
       '3502 hello https:example.com/blah']

df = pd.DataFrame([x.split(' ') for x in lst],
                  columns=['code', 'name', 'url'])

df['code-url'] = list(zip(df['code'], df['url']))
d = df.groupby('name')['code-url'].apply(list).to_dict()

# {'hello': [('0022', 'https:example.com/blah'),
#            ('3502', 'https:example.com/blah')],
#  'john':  [('0122', 'https:example.com/blah')]}