Iterating Over Dictionaries. How to print the values of the movies?


#1

Continuing the discussion from Iterating Over Dictionaries. How to print all the elements of movies?:



Replace this line with your code.

movies = {
"Monty Python and the Holy Grail": "Great",
"Monty Python's Life of Brian": "Good",
"Monty Python's Meaning of Life": "Okay"
}
print filter(lambda x: movies.items(), movies)

Hi I am unable to print values with the above code..its just showing only the keys not the values.

Getting this error message - "Oops, try again. It looks like you didn't print out all the keys and values in movies. You should have printed something like this: [("Monty Python's Life of Brian", 'Good'), ("Monty Python's Meaning of Life", 'Okay'), ('Monty Python and the Holy Grail', 'Great')]."

Can anyone help please??


#2

If you have the key, can you use that to get the values?

You can iterate through the values directly as well, or both. You can google for how to do that, there's sure to be some stack overflow question asking the same thing. You can look up the documentation for dict attributes: https://docs.python.org/2/library/stdtypes.html#mapping-types-dict
You can print out the attributes of a dict:

>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

The names with underscores are not meant to be used directly, the normal names at the end say quite a bit about what you can do with a dict, and if you want to know the details you can google for them, or call help:

>>> help({}.pop)
Help on built-in function pop:

pop(...)
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised

#3

Thanks for your reply :slight_smile:


#4

print movies.item()

Thats the fastest way. Check hint.


#5

print movies.item() doesn't work!
it has to be:
print movies.items()


#6

lol why are your answers always irrelevant?


#7

he not tell you the answer, he teach you the method.


#8