简体   繁体   中英

Converting Keys and Values of the same length into Dictionary form

I have a function with two arguments:

  • keys (ie ['a','b','c'] )
  • values to be put into a dictionary (ie [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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM