试图实现将电话簿的嵌套列表转换为字典的功能



我正在尝试编写一个函数,该函数接收电话簿的嵌套列表,并将其转换为python字典,以便我可以按名称进行搜索。

例如:

phonebook = [["Office", '461888', '61555', '612444'],["Home",'1', '743369'],["School",'7891525', '4771366'], ["Friend1",'556', '4102'],["Friend2",'4007']]
def python_dictionary(phn=phonebook):

如何继续?

def python_dictionary(phn):
res = dict()
for item in phn:
res[item[0]] = item[1:]
return res   

您可以获取电话簿的每个元素,并将其转换为类似的字典:

def python_dictionary(phn=phonebook):
#Create the phonebook array
phn_arr=[]
for contact in phn:
#create every contact dictionary
contact_dic={}
#add the name
contact_dic["name"]=contact[0]
#add the nums using for_loop
for i in range(2, len(contact)):
contact_dic["num"+str(i-1)]=contact[i]
#add the contact to the phn_dic
phn_arr.append(contact_dic)
#finaly return phn_arr
return phn_arr

注:

  • 此代码将返回联系人字典的数组
  • 如果在给定的电话簿中,联系人没有以名称开头,这将是有问题的,因为此代码考虑每个联系人(在格式列表中(的第一个元素的名称位于索引0

最新更新