Stack Overflow Asked by codemachine98 on December 11, 2020
I have a function with two arguments:
['a','b','c']
)[1,2,3]
)and if the lists are the same length, I put them in dictionary form and return the dictionary. Otherwise, I return the keyword None
from the function.
def dict_build(keys,values):
keys = ['']
values = []
dictionary = dict(zip(keys, values))
if len(keys) == len(values):
return dictionary
else:
return None
print(dict_build(['a','b','c'],[1,2,3])== { 'a': 1,'b': 2,'c': 3 })
# False
The output here should be True
as the lists have the same length. Where am I going wrong here?
Your function immediately overwrites the keys
and values
parameters with empty lists, so you always return an empty dictionary.
Just deleting the first two lines of the function should fix it. You could also shorten it down further to just:
def dict_build(keys,values):
if len(keys) == len(values):
return dict(zip(keys, values))
else:
return None
Correct answer by Samwise on December 11, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP