Search code examples
python-3.xlistfunctiondictionarynonetype

How to define a function that will convert list into dictionary while also inserting 'None' where there is no value for a key (Python3)?


Say we have a contact_list like this:

[["Joey", 30080],["Miranda"],["Lisa", 30081]]

So essentially "Miranda" doesn't have a zipcode, but with the function I want to define, I'd like it to automatically detect that and add "None" into her value slot, like this:

{
"Joey": 30080,
"Miranda": None,
"Lisa": 30081
}

So far I have this, which just converts the list to a dict:

def user_contacts(contact_list):
    dict_contact = dict(contact_list)
    print(dict_contact)

Not sure where I go from here, as far as writing in the code to add the None for "Miranda". Currently, I just get an error that says the 1st element ("Miranda") requires two lengths instead of one.

Eventually I want to just a pass any list like the one above in the defined function: user_contacts and, again, be able to get the dictionary above as the output.

user_contacts([["Joey", 30080],["Miranda"],["Lisa", 30081]]) 

Solution

  • so here is what you can do. you can check to see if the len of a certain element in your list, meets the expectations (in this case, 2 for name and zipcode). then if it fails the expectations, you can add "none":

    contacts = [["Joey", 30080], ["Miranda"], ["Lisa", 30081]]
    contacts_dict = {}
    for c in contacts:
        if len(c) < 2:
            c.append('None')
        contacts_dict.update({c[0]: c[1]})
    print(contacts_dict)
    

    and the output is:

    {'Joey': 30080, 'Miranda': 'None', 'Lisa': 30081}