MBakir
MBakir

Reputation: 57

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

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?

Upvotes: 3

Views: 68

Answers (5)

Edward Aung
Edward Aung

Reputation: 3512

Try this:

my_dict = {}
for key, value in zip(last_names, university):
    if key in my_dict:
        old_value = my_dict[key]
        if isinstance (old_value, str):
            my_dict[key] = [old_value, value]
        else:
            old_value.add (value)
    else:
        my_dict[key] = value

Upvotes: 0

AJNeufeld
AJNeufeld

Reputation: 8695

Assuming, as the question seems to imply, that a list is not desired if only one value is present for a key, a simple flattening post-step can be used to achieve the specified result.

from collections import defaultdict

d = defaultdict(list)
for k, v in zip(last_names, university):
   d[k].append(v)

# flatten single entry lists back to a string
d = { k: v[0] if len(v) == 1 else v for k, v in d.items() }

Upvotes: 0

Netwave
Netwave

Reputation: 42708

Use defaultdict

from collections import defaultdict

d = defaultdict(list)
for k, v in zip(last_names, university):
    d[k].append(v)

Upvotes: 5

blhsing
blhsing

Reputation: 106553

You can use the dict.setdefault method to initialize new keys with sub-lists:

dictionary = {}
for k, v in zip(last_names, university):
    dictionary.setdefault(k, []).append(v)

Upvotes: 1

Barmar
Barmar

Reputation: 781004

You need to set the value to a list, and check whether the key already exists and append to it.

dictionary = {}
for key, value in zip(last_names, university):
    if key in dictionary:
        dictionary[key].append(value)
    else:
        dictionary[key] = [value]

This will make all the values lists. It's generally easier if you're consistent about your data format, not mixing strings and lists. So the result will be:

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

Upvotes: 0

Related Questions