Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. # Andrew, use this link:
  2. # https://lmgtfy.com/?q=python+how+to+loop+through+attributes+in+a+dictionary
  3. # and for help with syntax, check out w3schools:
  4. # https://www.w3schools.com/python/python_for_loops.asp
  5.  
  6. def my_filter():
  7.     mydict = {"a": 1, "b": 2, "c": 3}
  8.     for thing in mydict.items():
  9.         print(thing)
  10. # outputs:
  11. # ('a', 1)
  12. # ('b', 2)
  13. # ('c', 3)
  14.  
  15. def my_filter():
  16.     mydict = {"a": 1, "b": 2, "c": 3}
  17.     for attr, val in mydict.items():
  18.         print(attr)
  19.         print(val)
  20. # outputs:
  21. # a
  22. # 1
  23. # b
  24. # 2
  25. # c
  26. # 3
  27.  
  28. def my_filter(limit):
  29.     mydict = {"a": 1, "b": 2, "c": 3}
  30.     for attr, val in mydict.items():
  31.         if val <= limit:
  32.             print(val)
  33.  
  34. my_filter(2)
  35. # outputs:
  36. # 1
  37. # 2
  38.  
  39. # takes in a limiting value, some integer
  40. # returns all values from a dictionary that are
  41. # less than or equal to the limit.
  42. def my_filter(limit):
  43.     # dictionary to search over
  44.     mydict = {"a": 1, "b": 2, "c": 3}
  45.     # dictionary holding matches
  46.     output = {}
  47.     for attr, val in mydict.items():
  48.         if val <= limit:
  49.             output[attr] = val
  50.  
  51.     return output
  52.  
  53. matches = my_filter(2)
  54. print(matches)
  55. # outputs:
  56. # {'a': 1, 'b': 2}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement