![](/img/trans.png)
[英]How can I sort the keys of a dictionary having same values based on the length of the keys?
[英]Converting Keys and Values of the same length into Dictionary form
我有一个带有两个参数的函数:
['a','b','c']
)[1,2,3]
) 如果列表长度相同,我将它们放入字典形式并返回字典。 否则,我会从函数中返回关键字None
。
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
此处的输出应为True
因为列表具有相同的长度。 我哪里出错了?
您的函数会立即用空列表覆盖keys
和values
参数,因此您始终返回一个空字典。
只需删除函数的前两行就可以修复它。 您还可以将其进一步缩短为:
def dict_build(keys,values):
if len(keys) == len(values):
return dict(zip(keys, values))
else:
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.