Home > Back-end >  python 3 - how to split a key in a dictionary in 2
python 3 - how to split a key in a dictionary in 2

Time:08-10

This is my first post, so if I miss something, let me know.

I'm doing a CS50 beginner python course, and I'm stuck with a problem.

Long story short, the problem is to open a csv file, and it looks like this:

name,house

"Abbott, Hannah",Hufflepuff

"Bell, Katie",Gryffindor .....

So I would love to put into a dictionary (which I did), but the problem now is that I supposed to split the "key" name in 2.

Here is my code, but it doesn't work:

before = []

....

    with open(sys.argv[1]) as file:

        reader = csv.reader(file)
        for name, house in reader:
            before.append({"name": name, "house": house})

        # here i would love to split the key "name" in "last", "first"

        for row in before[1:]:
            last, first = name.split(", ")

Any advice?

Thank you in advance.

CodePudding user response:

After you have the dictionary with complete name, you can split the name as below:

before = [{"name": "Abbott, Hannah", "house": "Hufflepuff"}]

# Before split
print(before)

for item in before:
    # Go through each item in before dict and split the name
    last, first = item["name"].split(', ')

    # Add new keys for last and first name
    item["last"] = last
    item["first"] = first

    # Remove the full name entry
    item.pop("name")

# After split
print(before)

You can also do the split from the first pass, e.g. store directly the last and first instead of full name.

  • Related