Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Christian Barry
PLUS
Christian Barry
Courses Plus Student 3,403 Points

Help refactoring because spaghetti code (splitsville code challenge)

I completed the challenge but was wondering if it could be refactored for readability/better code.

Create a function called splitsville. It will take 1 parameter, an address. For example: '100 E > Main St, Anywhereville, Oregon, 22222'.

Split the string into the street, city, state, and zip.

Return a dictionary with the keys street, city, state, zip_code and the values from the split > string. Example: {'street': '100 E Main St', etc.}

def splitsville(address):
    elements_dict = {"street": "", "city": "", "state": "", "zip_code": ""}
    split = address.split(", ")

    count = 0
    for key in elements_dict.keys():
        elements_dict.update({key: split[count]})
        count += 1


    return elements_dict

1 Answer

Steven Parker
Steven Parker
217,443 Points

I'm not sure why this would be called "spaghetti code", it seems pretty concise.

My only suggestion for improvement is that the element names don't have to be a dictionary themselves. The could just be a plain list, which would eliminate needing to also store empty values.