John Doe John Doe - 3 months ago 6
Python Question

How can I organize case-insensitive text and the material following it?

I'm very new to Python so it'd be very appreciated if this could be explained as in-depth as possible.

If I have some text like this on a text file:

matthew : 60 kg
MaTtHew : 5 feet
mAttheW : 20 years old
maTThEw : student
MaTTHEW : dog owner


How can I make a piece of code that can write something like...

Matthew : 60 kg , 5 feet , 20 years old , student , dog owner


...by only gathering information from the text file?

Answer
def test_data():
    source = \
    """
matthew : 60 kg
MaTtHew : 5 feet
mAttheW : 20 years old
maTThEw : student
MaTTHEW : dog owner
bob : 70 kg
BoB : 6 ft
    """

    return source.split("\n")

def append_pair(d, p):
    k, v = p
    if k in d:
        d[k] = d[k] + [v]
    else:
        d[k] = [v]
    return d


if __name__ == "__main__":
    pairs = [[x.strip().lower() for x in line.split(":", 2)] for line in test_data()]
    cleaned_pairs = [p for p in pairs if len(p) == 2]
    d = reduce(append_pair, cleaned_pairs, {})
    for k, v in d.items():
        print("{}: {}".format(k, ", ".join(v)))