Guest User

Untitled

a guest
Apr 23rd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. ## By default, iterating over a dict iterates over its keys.
  2. ## Note that the keys are in a random order.
  3. for key in dict: print key
  4. ## prints a g o
  5.  
  6. ## Exactly the same as above
  7. for key in dict.keys(): print key
  8.  
  9. ## Get the .keys() list:
  10. print dict.keys() ## ['a', 'o', 'g']
  11.  
  12. ## Likewise, there's a .values() list of values
  13. print dict.values() ## ['alpha', 'omega', 'gamma']
  14.  
  15. ## Common case -- loop over the keys in sorted order,
  16. ## accessing each key/value
  17. for key in sorted(dict.keys()):
  18. print key, dict[key]
  19.  
  20. ## .items() is the dict expressed as (key, value) tuples
  21. print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
  22.  
  23. ## This loop syntax accesses the whole dict by looping
  24. ## over the .items() tuple list, accessing one (key, value)
  25. ## pair on each iteration.
  26. for k, v in dict.items(): print k, '>', v
  27. ## a > alpha o > omega g > gamma
Add Comment
Please, Sign In to add comment