1

I'm trying to add the values from a dictionary into a new list, but without anything remotely fancy, including the value method. I was able to add the keys to a new list with newList.append(item) in a for loop. But I'm trying to add the values to a separate list. Here is the problem I'm solving along with my code so far:

If you remember, the .items() dictionary method produces a sequence of tuples. Keeping this in mind, we have provided you a dictionary called pokemon. For every key value pair, append the key to the list p_names, and append the value to the list p_number. Do not use the .keys() or .values() methods.

pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126}

p_names = []
p_number = []

for item in pokemon:
    p_names.append(item)
BintAmun
  • 63
  • 2
  • 9
  • 3
    Your question has the hint that basically tells you what you need to do. Use the `.items()` method – rdas May 17 '20 at 13:55

6 Answers6

5

As the question prompt says you need to use .items method which returns the key-value pair as a tuple:

for k, v in pokemon.items():
    p_names.append(k)
    p_number.append(v)
xcmkz
  • 677
  • 4
  • 15
2

You need to use items that returns both the key and the value.

for k, item in pokemon.items():
    p_names.append(k)
    p_number.append(item)

print (p_number)

# [19, 66, 86, 86, 126]
Sheldore
  • 37,862
  • 7
  • 57
  • 71
0
for name, number in pokemon.items():
    p_names.append(name)
    p_number.append(number)
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
0
pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126}


p_names = list()
p_number = list()


for k, v in pokemon.items():
    p_names.append(k)
    p_number.append(v)


print(p_names)
print(p_number)
  • 1
    It would be very helpful if you could also explain in words what was wrong in the original code, and how the changes in your code solve the issue. – G. Sliepen May 22 '20 at 20:28
  • The program is structured and complete with the print function.I thought is it helpful to understand for the beginners level programmer. – Bibek Neupane May 23 '20 at 09:04
  • Just presenting a solution without any explanation only teaches one that a solution exists, not what was wrong with the original solution, nor how to solve similar problems in the future. – G. Sliepen May 24 '20 at 14:56
  • 1
    Thank you @G.Sliepen for letting me know the best possible way to use stack overflow. It was my first post, will help me in future. – Bibek Neupane May 24 '20 at 16:07
0
pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126}
p_names=[]
p_number=[]
new_pokemon=pokemon.items()
for i, j in new_pokemon:
    p_names.append(i)
    p_number.append(j)
print(p_names)
print(p_number)
0

pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126}

 p_names=[]
 p_number=[]
 for k,v in pokemon.items():
        p_names.append(k)
        p_number.append(v)
parvel
  • 11
  • 1
  • 6