TundraMike
TundraMike

Reputation: 11

Creating a Dictionary using list1 as keys and list2 as values

Complete the function to return a dictionary using list1 as the keys and list2 as the values

def createDict(list1, list2):
    my_dict = {'list1':'list1'}
    my_dict.update({'list1':list2})
    return my_dict 

createDict(['tomato', 'banana', 'lime'], ['red','yellow','green'])




# expected output: {'tomato': 'red', 'banana': 'yellow', 'lime': 'green'}

# getting {'list1': ['red', 'yellow', 'green']}

Upvotes: 0

Views: 1764

Answers (2)

Primusa
Primusa

Reputation: 13498

Use zip and dict:

l1 = [1, 2, 3]
l2 = [4, 5, 6]

print(dict(zip(l1, l2)))

Output:

{1: 4, 2: 5, 3: 6}

This works because the dict constructor takes key-value tuples:

d = dict([(1, 4), (2, 5), (3, 6)])
print(d)

Output:

{1: 2, 3: 4, 5: 6}

zip combines two lists into tuple pairs:

print(list(zip([1, 2, 3], [4, 5, 6]))

Output:

[(1, 4), (2, 5), (3, 6)]

The combination of these two functions builds your dictionary.

Upvotes: 4

jsbueno
jsbueno

Reputation: 110726

You can use the "dict comprehension" special syntax:

my_dict = {key: value for key, value in zip(list1, list2)}

Or call the dict builtin with a packing of the keys and values:

my_dict = dict(zip(list1, list2))

In both cases, the key is the zip built-in, which given two or more iterables will pick one item from each of them and pack them in a (usually temporary) tuple. The dict built-in consumes the iterable of 2-tuples and interpret then as key/value pairs. And in the dict-comprehension syntax, we explicitly use each component of the tuple generated by zip as key and value.

Upvotes: 1

Related Questions