Search code examples
pythondictionaryfor-loopnested-listsis-empty

Create a function that loops through a nested list and return a dictionary: Empty elements in list return a none in dictionary


I am using Python 3. I need to create a function: contacts() that loops through a nested list and returns a dictionary of an item for each contact name and area-code. If the data does not include area code (empty element) then the value should be None.

My starting list is:

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

My return dictionary should be:

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

I am very new to python (I have used R in the past). I am hoping someone could help me solve this problem. It seems very simple but I am getting stuck at the point where my loop has to handle the empty value.

This is my most recent attempt:

none= None

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

But this returns:

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

Solution

  • Assuming you'll never have repeated names in your 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