【问题标题】:Create a function that loops through a nested list and return a dictionary: Empty elements in list return a none in dictionary创建一个遍历嵌套列表并返回字典的函数:列表中的空元素在字典中返回无
【发布时间】:2020-06-28 15:04:49
【问题描述】:

我正在使用 Python 3。我需要创建一个函数contacts(),它遍历嵌套列表并为每个联系人姓名和区号返回一个项目的字典。如果数据不包含区号(空元素),则值应为None

我的首发名单是:

contact_list = [["Mike Jordan", 310], ["Jay Z"], ["Oprah Winfrey", 213], ["Leo DeCaprio", 212]]

我的返回字典应该是:

{
    "Mike Jordan": 310,
    "Jay Z": None,
    "Oprah Winfrey": 213,
    "Leo DeCaprio": 212,    
}

我对 python 很陌生(我过去使用过 R)。我希望有人能帮我解决这个问题。这看起来很简单,但我被困在我的循环必须处理空值的地方。

这是我最近的尝试:

none= None

def contacts(contact_list):
  for list in contact_list:
    if len(list) == 2:
      print(list)
    else:
      print(None)

但这会返回:

['Mike Jordan', 310]
None
['Oprah Winfrey', 213]
['Leo DeCaprio', 212]

【问题讨论】:

  • 您期望的输出是什么?该程序似乎正在做它应该做的事情。 P.S.:避免使用 list 作为名称/变量。它是创建列表的函数的保留关键字。
  • @navneethc。我正在尝试获取字典,并且我希望该字典包含名称和区号。如果没有区号(即“Jay Z”),我希望字典返回无。现在我只创建了列表,并且缺少 Jay Z 条目,因为区号没有与名称关联的值。
  • 我看到您的问题的解决方案已发布。也就是说,这里是学习如何创建、访问和修改字典的好地方:realpython.com/python-dicts

标签: python dictionary for-loop nested-lists is-empty


【解决方案1】:

假设您的 contact_list 中永远不会有重复的名字

def contacts(contact_list):
    contact_dict = {}
    for contact in contact_list:
        try:
            contact_dict[contact[0]] = contact[1]
        except IndexError:
            contact_dict[contact[0]] = None
    return contact_dict

【讨论】:

  • 谢谢!这正是我需要的。
  • 没问题 - 在 Python 中使用 try / except 进行测试是很常见的(有点“先做,后问问题”) - 请参阅 Is it a good practice to use try except else in python 了解更多信息.如果此答案对您有所帮助,请考虑接受它作为答案(左侧按钮)。谢谢。
猜你喜欢
  • 2021-10-21
  • 2019-02-12
  • 1970-01-01
  • 2012-07-09
  • 2015-12-06
  • 2020-10-16
  • 2021-05-20
  • 2021-03-19
  • 2020-03-10
相关资源
最近更新 更多