priya
priya

Reputation: 93

Convert 2 lists into a dictionary using dictionary comprehension

I have 2 lists which i want to convert to a dictionary using dictionary comprehension.

aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]

Output should be like:

{50769054:['07:51:59'], 183926374:['07:53:35', '07:55:20', '08:01:48']}

I am trying this way:

dictionary ={}
{bb[k]:aa[k] if bb[k] not in dictionary.keys() else dictionary[bb[k]].append(aa[k]) for k in range(0,4)}

But it is giving me single values only. My output:

{50769054: ['07:51:59'], 183926374: ['08:01:48']}

Upvotes: 0

Views: 69

Answers (2)

Vinay Gupta
Vinay Gupta

Reputation: 809

@Sushanth's solution is accurate. In that extend, you can use comprehension like this:

from collections import defaultdict

aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]

dictionary = defaultdict(list)
[dictionary[y].append(x) for x, y in zip(aa, bb)]

print(dict(dictionary))

Output:

{50769054: ['07:51:59'], 183926374: ['07:53:35', '07:55:20', '08:01:48']}

Upvotes: 1

sushanth
sushanth

Reputation: 8302

try this, defaultict with zip

from collections import defaultdict

aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]

result = defaultdict(list)

for x, y in zip(aa, bb):
    result[y].append(x)

defaultdict(<class 'list'>, {50769054: ['07:51:59'], 183926374: ['07:53:35', '07:55:20', '08:01:48']})

Upvotes: 1

Related Questions