Reputation: 61
I have 2 lists as inputs:
A = ['A', 'B', 'C', 'D', 'E']
sessionid = [1, 1, 3, 2, 2]
I want to use dictionary comprehension without importing any libraries to generate the following output, with the key as 'Session x' by using string formatting:
{'Session 1': ['A','B'], 'Session 2': ['D','E'], 'Session 3': ['C']}
I tried with this code:
dictb = {'Session {}'.format(session): [a if session not in dictb.keys() else [a]] for a,session in list(zip(A,sessionid))}
but it returns me this:
{'Session 1': ['B'], 'Session 3': ['C'], 'Session 2': ['E']}
I think there is a problem with if-else statement
in the comprehension. How should I improve this?
Upvotes: 1
Views: 557
Reputation: 61
This is because you're generating a dictionary with string keys that have the format Session{}
and checking if the dictionary has integer keys, which it always doesn't and thus takes the part after else
. When the same integer comes, it updates the value and that's why you're seeing the last updated value. I wouldn't recommend doing what you want using a dict comprehension, for both performance and readability reasons but if you really want to, try (Not tested):
dictb = {'Session {}'.format(session): [dictb['Session {}'.format(session)] + [a] if 'Session {}'.format(session) not in dictb.keys() else [a]] for a,session in list(zip(A,sessionid))}
The recommended approach would be:
dictb = {}
for a, session in zip(A, sessionid):
key = 'Session {}'.format(session)
if key in dictb:
dictb[key].append(a)
else:
dictb[key] = [a]
Upvotes: 0
Reputation: 15364
Here is a possible solution:
dictb = {f'Session {k}': [v for v, i in zip(A, sessionid) if k == i]
for k in sorted(set(sessionid))}
Output:
{'Session 1': ['A', 'B'], 'Session 2': ['D', 'E'], 'Session 3': ['C']}
Upvotes: 1