I'm creating a dictionary where if the key has an 'R' then one list, otherwise it goes in the list for 'E'. My code so far:
d1 = {'SSW 540': ['E', 'SYEN'], 'SSW 564': ['R', 'SFEN'], 'SSW 567': ['R', 'SFEN'], 'CS 501': ['E', 'SFEN']}
rlist = []
elist = []
for k, v in d1.items():
if v[0] == 'R':
rlist.append([v[1], k])
elif v[0] == 'E':
elist.append([v[1], k])
Output is:
rlist = [['SFEN', 'SSW 564'], ['SFEN', 'SSW 567']]
elist = [['SYEN', 'SSW 540'], ['SFEN', 'CS 501']]
How could I create two dictionaries, call them rdict and edict where:
rdict = {'SFEN': ['SSW 564','SSW 567']}
edict = {'SYEN': ['SSW 540'], 'SFEN': ['CS 501']}
There could be more values than just 'SYEN' and 'SFEN' so it needs to be any particular first element in the list.
If I try something like:
mlist = {}
for list in rlist:
if list[0] in rlist:
mlist.append(list[1])
else:
mlist[list[0]].append(list[1])
I get KeyError: 'SFEN'. Could I use defaultdict for this?