-1

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]
  • 1
    What is it that you are expecting as output? The program seems to be doing exactly what it's supposed to do. P.S.: Avoid using `list` as a name/variable. It's a reserved keyword for the function that creates lists. – navneethc Jun 28 '20 at 15:08
  • @navneethc. I am trying to get a dictionary, and I want that dictionary to include the names and area codes. Where there is no area code (i.e. "Jay Z") I would like the dictionary to return None. Right now I have only created lists and the Jay Z entry is missing because the area code has no value associated with the name. – Whitney Jun 28 '20 at 15:11
  • I see a solution to your problem has been posted. That said, here's a good place to learn about how to create, access and modify dictionaries: https://realpython.com/python-dicts/ – navneethc Jun 28 '20 at 15:16

1 Answers1

0

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
hemmelig
  • 240
  • 2
  • 8
  • **Thank you!** This is exactly what I needed. – Whitney Jun 28 '20 at 15:17
  • No problem - it is very common in Python to use `try` / `except` over testing (kind of a 'do first, ask questions later') - see [Is it a good practice to use try except else in python](https://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python) for more on that. If this answer has helped you, please consider accepting it as the answer (button to the left). Thanks. – hemmelig Jun 28 '20 at 15:26