Example 1: Access both key and value using items()
Output
a juice b grill c corn
- Using a for loop, pass two loop variables
keyandvaluefor iterabledt.items().items()returns thekey:valuepairs. - Print
keyandvalue.
Example 2: Access both key and value without using items()
Output
a juice b grill c corn
- Iterate through the dictionary using a for loop.
- Print the loop variable
keyand value atkey(i.e.dt[key]).
However, the more pythonic way is example 1.
Example 3: Access both key and value using iteritems()
Output
a juice b grill c corn
It works for python 2 versions.
As in Example 1, we can use iteritems() for python 2 versions.
Example 4: Return keys or values explicitly
Output
a b c juice grill corn
You can use keys() and values() to explicitly return keys and values of the dictionary respectively.