Apotheosis
Apotheosis

Reputation: 21

List of integers in dictionary python

i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the favorite numbers list twice in list form. How do i fix this so it prints it only once, and plainly without the brackets?

here is my code so far.

favorite_numbers = {
    'king': ['7','10'],
    'jake': ['29','77'],
    'mr robot': ['234','1337'],
    'elliot': ['1234' ,'89'],
}

for name, number in favorite_numbers.items():
    print(
    "Hey, " 
    + name.title() + 
    " your favorite numbers are: "
    )
    for numbers in number:
        print(number)

Help? please and thank you.

Upvotes: 0

Views: 486

Answers (3)

David
David

Reputation: 1234

I think your naming confused you a little. Look at your use of number and numbers. Fixed version below. Also check out `print( "foo", end = "" ) to have multiple print statements that don't terminate in a new line, if you want to clean up the appearance of the output a little.

favorite_numbers = {
    'king': ['7','10'],
    'jake': ['29','77'],
    'mr robot': ['234','1337'],
    'elliot': ['1234' ,'89'],
}

for name, numbers in favorite_numbers.items():
    print(
    "Hey, " 
    + name.title() + 
    " your favorite numbers are: "
    )
    for number in numbers:
        print(number)

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168716

You are confused because you have similarly-named variables. In your case, this line:

for name, number in favorite_numbers.items():

binds number to successive values in the dictionary. In this example, they are specifically lists containing strings.

This line:

for numbers in number:

binds numbers to successive strings in the list.

This line:

print(number)

prints the list, not the string.

Try this:

for name, list_of_numbers in favorite_numbers.items():
    print(
    "Hey, " 
    + name.title() + 
    " your favorite numbers are: "
    )
    for number in list_of_numbers:
        print(number)

Upvotes: 0

user94559
user94559

Reputation: 60143

This will fix your current code:

for numbers in number:
    print(numbers)

But it's kind of a backward way to name the variables. How about this instead?

for name, numbers in favorite_numbers.items():
    print(
    "Hey, " 
    + name.title() + 
    " your favorite numbers are: "
    )
    for number in numbers:
        print(number)

Upvotes: 1

Related Questions