Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dictionary from two lists in python while maintaining all key value information?

Tags:

python

Example:

last_names = ['Bakir','Jose','Jose','Pierce']

university = ['Davis', 'Stanford', 'George Town', 'Berkeley']

Desire the Following

resulting_dictionary = {'Bakir':'Davis', 'Jose': ['Stanford', 'George Town'], 'Pierce':'Berkeley'}

I've tried the following

dictionary = {key:value for key, value in zip(last_names, university)}

But obtained the following:

{'Bakir': 'Davis', 'Jose': 'George Town', 'Pierce': 'Berkeley'}

Due to duplicate key value in last name list.

Thoughts?

like image 373
MBakir Avatar asked Jun 29 '26 12:06

MBakir


1 Answers

Use defaultdict

from collections import defaultdict

d = defaultdict(list)
for k, v in zip(last_names, university):
    d[k].append(v)
like image 68
Netwave Avatar answered Jul 02 '26 02:07

Netwave