Search code examples
pythonstring-concatenation

Python Printing Elements from a dictionary produces error


I created this block of code for usernames which is read using a loop.

users = {
    'aeinstein': {
        'first':'albert',
        'last':'einstein',
        'location':'princeton'
        },
    'mcurie': {
        'first':'marie',
        'last':'curie',
        'location':'paris',
        }
    }

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'], user_info['last']
    location = user_info['location']

    print("\tFull name:" + full_name.title())
    print("\tLocation:" + location.title())

Now, if you observe the following line in the for loop

full_name = user_info['first'], user_info['last']

I expect1 this to append the value albert einstein and marie curie, but this produces the error

print("\tFull name:" + full_name.title())
AttributeError: 'tuple' object has no attribute 'title'

but why is my method wrong and the following therefore correct...

full_name = user_info['first'] + " " + user_info['last']

to produce the following result

Username: aeinstein
    Full name:Albert Einstein
    Location:Princeton

Username: mcurie
    Full name:Marie Curie
    Location:Paris

1From the comments: so when you do say print("hello", "world") this type of string concatenation works right but not in the example that I have shown?


Solution

  • The expression user_info['first'], user_info['last'] creates a tuple of two elements (in this case the elements are strings). Tuple object does not have the title method but if you concatenate with the plus operator like you do user_info['first'] + " " + user_info['last'], you create a String and not a tuple so you can use the title method