patternpythonMinor
Creating a dictionary from two lists
Viewed 0 times
creatingtwolistsdictionaryfrom
Problem
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.
I was hoping for to get some feedback.
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 dictionaryI was hoping for to get some feedback.
Solution
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:
Btw I renamed the function with
Another alternative somewhat more compact alternative is using
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)]))Code Snippets
def create_dict(keys, values):
return dict(zip(keys, values + [None] * (len(keys) - len(values))))from itertools import zip_longest
def create_dict(keys, values):
return dict(zip_longest(keys, values[:len(keys)]))Context
StackExchange Code Review Q#93880, answer score: 7
Revisions (0)
No revisions yet.