Print Multiple Values

Is there a way to print value from multiple items without writing “print” command multiple times?
For example: this exercise asks to print the values of dictionary items"Sloth",“Puffin”, and “Burmese Python”. is there a shortcut for calling their values to all print with one ‘print’ call?
I tried “print residents[“Sloth” , “Puffin” , “Burmese Python”]” but it runs an error

you could use a loop, see the python docs:

5. Data Structures — Python 2.7.18 documentation

what you look for:

if you just want the keys, there is also the .keys() method

1 Like

would the same be possible for deleting items?

and what exactly would the keys be in the above example?

Depends on what the objective is, but yes, certainly possible. You could make a list with items you want to remove, something like this:

entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
    for key in entries:
        if key in the_dict:
            del the_dict[key]

or this:

d = {'some':'data'}
entriesToRemove = ('any', 'iterable')
for k in entriesToRemove:
    d.pop(k, None)

so there are (2) different ways i found to avoid typing print twice when calling values by their key pairs.

  1. single string:
print residents['Sloth'], residents['Burmese Python']
  1. for loop:
for animal in residents:
  if animal in ('Sloth','Burmese Python'):
    print residents[animal]

The main difference between the two being their output, 1 prints all to a single line, 2 prints each value to a separate line.

1 Like

Hi @blogplayer50871, and welcome to the Codecademy Forums!

Below is another way it can be done, though it is admittedly not good programming style. It will work in Python 3, but not in Python 2.

[print(residents[key]) for key in ('Sloth','Burmese Python')]

The above list comprehension calls the Python 3 print function for each of specified keys in residents.

Edited on November 2, 2019 to limit the output to the values associated with the specified keys