Code to generate a dictionary from two lists I created a script to perform a union on 2 lists: keys and words. I needed to create a dictionary from them. If there are more keys than words, missing words are replaced with "None". Any excess words are removed.

How can I improve this code to be more compact and perform better? 

#! /usr/bin/env python3
import random
import string
from itertools import zip_longest
def generator(listKeys,listWords):

    diff = len(listKeys)-len(listWords)
    if diff &gt; 0:
        for i in range(0,diff):
            listWords.append(None)
    elif diff&lt;0:
        listWords = listWords[0:len(listKeys)]

    done = dict(zip(listKeys,listWords))
    return done

if __name__ == "__main__":
    listKeys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
    listWords = [94, 87, 92, 5, 75, 91, 60, 5]
    print("Keys more values:\nKeys: %s \nValues %s\nResult: %s\n" % (listKeys, listWords,generator(listKeys,listWords)))

    listKeys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
    listWords = [9, 65, 18, 80, 2, 16, 81, 98, 73, 2, 88, 30, 1, 78, 92]
    print("Values more keys:\nKeys: %s \nValues %s\nResult: %s\n" % (listKeys, listWords,generator(listKeys,listWords)))

    listKeys = []
    listWords = []

    for i in range(0,random.randrange(5,15)):
        listKeys.append(list(string.ascii_lowercase)[i])

    for i in range(0,random.randrange(6,16)):
        listWords.append(random.randrange(0,100))

    print("Random:\nKeys: %s \nValues %s\nResult: %s\n" % (listKeys, listWords,generator(listKeys,listWords)))
zip and itertools.zip_longest do exactly what you are looking for, you only need to choose between the two depending on the lengths of the lists:

def generator(listKeys, listWords):
    if len(listKeys) &gt; len(listWords):
        zipped = zip_longest(listKeys, listWords)
    else:
        zipped = zip(listKeys, listWords)
    return dict(zipped)


This can even be shortened to

def generator(listKeys, listWords):
    my_zip = zip_longest if len(listKeys) &gt; len(listWords) else zip
    return dict(my_zip(listKeys, listWords))


Note that generator is not a good name for this function as the word generator has a particular meaning in Python.