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

时间:2018-03-07 08:47:47

标签: python python-2.7 list dictionary structure

我对dicts有疑问。我是一个菜鸟,并且一直在仔细研究这个话题,但我似乎无法绕过它。我想要做的是从文本文件(1200万个术语)中获取这个巨大的列表,将其放入dict中,并获取具有某些特征的项目并将它们放入dict中的一个列表中,以便在我搜索时dict,显示具有该特征的每个元素。

一些列表元素的示例:

0022 hello https:example.com/blah

0122 john https:example.com/blah

3502 hello https:example.com/blah

现在根据上面的数据,我希望有一个dict元素,这是每次单词" hello"出现并与"你好"作为关键,所以当我搜索"你好"我会回来

0022 hello https:example.com/blah

3502 hello https:example.com/blah

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

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

2 个答案:

答案 0 :(得分:1)

正如所建议的那样,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

答案 1 :(得分:0)

以下是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')]}
相关问题