-1

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

Just completely lost on how to start this.

def createDict(list1, list2):
    # expected output: {'tomato': 'red', 'banana': 'yellow', 'lime': 'green'}  
    print(createDict(['tomato', 'banana', 'lime'], ['red','yellow','green']))        

    # expected output: {'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'}
    print(createDict(['Brazil', 'Ireland', 'Indonesia'], ['Brasilia','Dublin','Jakarta']))

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

    # expected output: {'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'}
martineau
  • 119,623
  • 25
  • 170
  • 301
MIKE S
  • 15
  • 1

3 Answers3

2

Use zip() to do it in the easiest pythonic way:

def createDict(list1, list2):
    return dict(zip(list1, list2))
Austin
  • 25,759
  • 4
  • 25
  • 48
1

It is a simple case of iterating over the first list, of keys, and assigning them the values of the second list. There are many ways to do this. The process looks something like this:

def createDict(list1, list2):
    outdict = {}  # define an empty dictionary to fill in and return
    for index, key in enumerate(list1):  # use items in list1, and their position
        outdict[key] = list2[index]      # assign the value
    return outdict

Of course, the most pythonic way to do this, is to use zip:

def createDict(list1, list2):
    return dict(zip(list1, list2))
sal
  • 3,515
  • 1
  • 10
  • 21
  • 1
    Oh god thanks so much. I was not seeing the zip method! Sometimes its right in your face. – MIKE S May 06 '19 at 17:28
0

E.g using dictionary comprehensions as described in this pep:

https://www.python.org/dev/peps/pep-0274/

def createDict(keys, values):
    return {k: v for k, v in zip(keys, values)}
knuesperli
  • 46
  • 4