Search code examples
pythonlistif-statementstring-formattingdictionary-comprehension

Dictionary returning only the Last Item in List Value


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?


Solution

  • 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']}