创建两个字典并从文本文件分配键和值

时间:2019-02-26 18:03:03

标签: python python-3.x dictionary

我必须创建两个字典并分配键和值。当键为员工ID时,该值为利息。然后,当关键是兴趣时,值将是员工ID。 然后,我必须打印这些词典。 我必须先打开/阅读文本文件。

到目前为止,我已经知道了:

file = open("interests.txt", "r")

people = {}

for row in file:
    employee_id = int(row[0])
    people[employee_id] = {
        'interests': row[2:]

        }

from pprint import pprint
pprint (people)

我只能这样做:

{0: {'interests': 'Cassandra\n'},
 1: {'interests': 'Postgres\n'},
 2: {'interests': 'pandas\n'},
 3: {'interests': 'probability\n'},
 4: {'interests': 'libsvm\n'},
 5: {'interests': 'programming languages\n'},
 6: {'interests': 'theory\n'},
 7: {'interests': 'neural networks\n'},
 8: {'interests': 'artificial intelligence\n'},
 9: {'interests': 'Big Data'}}

但是我必须获得与employee_id匹配的所有利益。

请帮助我。

2 个答案:

答案 0 :(得分:2)

您将使用dict来覆盖同一键的先前值。您可以改用dict.setdefault来初始化带有列表的字典新键的每个条目,以便您可以继续向其添加项:

people = {}
interests = {}
for line in file:
    employee_id, interest = line.split(maxsplit=1)
    employee_id = int(employee_id)
    interest = interest.rstrip()
    people.setdefault(employee_id, []).append(interest)
    interests.setdefault(interest, []).append(employee_id)

people变为:

{0: ['Hadoop', 'Big Data', 'HBas', 'Java', 'Spark', 'Storm', 'Cassandra'], 1: ['NoSQL', 'MongoDB', 'Cassandra', 'HBase', 'Postgres'], 2: ['Python', 'skikit-learn', 'scipy', 'numpy', 'statsmodels', 'pandas'], 3: ['R', 'Python', 'statistics', 'regression', 'probability'], 4: ['machine learning', 'regression', 'decision trees', 'libsvm'], 5: ['Python', 'R', 'Java', 'C++', 'Haskell', 'programming languages'], 6: ['statistics', 'probability', 'mathematics', 'theory'], 7: ['machine learning', 'scikit-learn', 'Mahout', 'neural networks'], 8: ['neural networks', 'deep learning', 'Big Data', 'artificial intelligence'], 9: ['Hadoop', 'Java', 'MapReduce', 'Big Data']}

interests变为:

{'Hadoop': [0, 9], 'Big Data': [0, 8, 9], 'HBas': [0], 'Java': [0, 5, 9], 'Spark': [0], 'Storm': [0], 'Cassandra': [0, 1], 'NoSQL': [1], 'MongoDB': [1], 'HBase': [1], 'Postgres': [1], 'Python': [2, 3, 5], 'skikit-learn': [2], 'scipy': [2], 'numpy': [2], 'statsmodels': [2], 'pandas': [2], 'R': [3, 5], 'statistics': [3, 6], 'regression': [3, 4], 'probability': [3, 6], 'machine learning': [4, 7], 'decision trees': [4], 'libsvm': [4], 'C++': [5], 'Haskell': [5], 'programming languages': [5], 'mathematics': [6], 'theory': [6], 'scikit-learn': [7], 'Mahout': [7], 'neural networks': [7, 8], 'deep learning': [8], 'artificial intelligence': [8], 'MapReduce': [9]}

答案 1 :(得分:0)

你在那儿。当您解析新行时,现在您要用全新的兴趣替换键处字典中的兴趣值。取而代之的是,让该键处的值成为一个列表,在该列表上添加新的利息值:

for row in file:
    employee_id = int(row[0])
    interest = row[2:]

    if employee_id not in people:
        people[employee_id] = []

    people[employee_id].append(interest)

有了这个,您将获得一个字典,每个ID映射到相应的兴趣。要拥有一个字典,其中每个兴趣都映射到相应的ID,您可以简单地反向进行相同的操作。 (我将作为学习练习留给您。:))