I have to create two dictionaries and assign key and values. When key is employee id, the value would be interest. Then, when key is interests the value would be employee id.
Then I have to print these dictionaries.
I have to open/read the text file first.
So, far I’ve got:
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)
I only this as a result:
{0: {'interests': 'Cassandran'},
1: {'interests': 'Postgresn'},
2: {'interests': 'pandasn'},
3: {'interests': 'probabilityn'},
4: {'interests': 'libsvmn'},
5: {'interests': 'programming languagesn'},
6: {'interests': 'theoryn'},
7: {'interests': 'neural networksn'},
8: {'interests': 'artificial intelligencen'},
9: {'interests': 'Big Data'}}
But I have to get all the interests that match with the employee_id.
Please help me.
2
Answers
You’re halfway there. When you parse new row, right now you are replacing the interest value in the dictionary at the key with an entirely new interest. Instead, have the value at that key be a list to which you append the new interest value:
With this, you will get a dictionary with each ID mapped to the corresponding interests. To have a dictionary where each interest is mapped to the corresponding IDs, you can simply do the same operation in reverse. (Which I will leave to you as a learning exercise. 🙂 )
You’re overwriting the previous values of the same key by using a dict of dicts. You can instead use
dict.setdefault
to initialize each entry of a new key of a dict with a list so that you can keep appending items to it:people
becomes:interests
becomes: