6
\$\begingroup\$

I have working code here which takes two lists and turns them into a dictionary with the first list being the keys and the second being the values. If the keys exceed the values the value "None" will be assigned to that key.

def createDict(keys, values):
    i = 0
    dictionary = {}

    # go through all the values in the first list
    for key in keys:
        # if our keys index is equal or exceeds our value list's length
        # then extend the list with a None value
        if i >= len(values):
            values.extend([None])
        dictionary[key] = values[i]
        i = i + 1
    return dictionary

I was hoping for to get some feedback.

\$\endgroup\$
3
  • 5
    \$\begingroup\$ dict(itertools.zip_longest(keys, values)) \$\endgroup\$ Jun 17, 2015 at 15:18
  • \$\begingroup\$ That's a legit answer @GarethRees (with a few extra words) \$\endgroup\$
    – janos
    Jun 17, 2015 at 15:28
  • \$\begingroup\$ It's not quite the same when keys is shorter than values. \$\endgroup\$ Jun 17, 2015 at 15:33

2 Answers 2

7
\$\begingroup\$

A common way to create a dictionary from two lists is zipping. The zip built in takes two lists and creates a list of pairs from them. In turn, a list of pairs can be used to create a dictionary directly.

Your case has an extra twist: we need to pad the list of values to the same length as the list of keys, otherwise the keys with no corresponding values would simply get dropped.

Even with this minor complication, the function can be written simpler quite easily:

def create_dict(keys, values):
    return dict(zip(keys, values + [None] * (len(keys) - len(values))))

Btw I renamed the function with snake_case to follow recommended PEP8 conventions.

Another alternative somewhat more compact alternative is using itertools.zip_longest:

from itertools import zip_longest


def create_dict(keys, values):
    return dict(zip_longest(keys, values[:len(keys)]))
\$\endgroup\$
0
0
\$\begingroup\$

This here is a very naive approach. Hope this helps.

def create_dict(a, b):
    d = dict()
    if len(a)-len(b) != 0:
        for i in range(len(a)-len(b)):
            b.append(None)
    for j in range(len(a)):
        d[a[j]] = b[j]
    return d

this function creates a dictionary from given two lists, it prepares a dict by considering the length of the lists. it prepares the dict only to the items present in the 1st list 'a'. If length of list 'b' is less than the length of list 'a', then it appends 'None' to 'b' to make its length equal to the length of list 'a'.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.