Advertisement
furas

Python - dict - search by value

Mar 17th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. data = {
  2.     'a': 'hello',
  3.     'b': 'world',
  4.     'c': 'hello'
  5. }
  6.  
  7. # ----- example 1 -----
  8.  
  9. # invert dictionary - it loses element 'hello':'a'
  10.  
  11. inverted_data = {val: key for key, val in data.items()}
  12.  
  13. print(inverted_data)
  14.  
  15. # {'hello': 'c', 'world': 'b'}
  16.  
  17. print(inverted_data.get("hello"))
  18.  
  19. # 'c'
  20.  
  21. print(inverted_data.get("other"))
  22.  
  23. # None
  24.  
  25. # ----- example 2 -----
  26.  
  27. # find all keys using "list comprehension"
  28.  
  29. result = [key for key, val in data.items() if val == "hello"]
  30.  
  31. print(result)
  32.  
  33. # ['a', 'c']
  34.  
  35. result = [key for key, val in data.items() if val == "other"]
  36.  
  37. print(result)
  38.  
  39. # []  # empty list
  40.  
  41. # --- example 3 ---
  42.  
  43. # find all keys using "for" loop
  44.  
  45. result = []
  46.  
  47. for key, val in data.items():
  48.     if val == "hello":
  49.         result.append(key)
  50.          
  51. print(result)
  52.  
  53. # ['a', 'c']
  54.  
  55. result = []
  56.  
  57. for key, val in data.items():
  58.     if val == "other":
  59.         result.append(key)
  60.          
  61. print(result)
  62.  
  63. # []  # empty list
  64.  
  65. # ----- example 4 -----
  66.  
  67. # invert dictionary using list as elements - it doesn't lose element 'hello':'a'
  68.  
  69. inverted_data = dict()
  70.  
  71. for key, val in data.items():
  72.     if val not in inverted_data:
  73.         inverted_data[val] = []
  74.     inverted_data[val].append(key)
  75.  
  76. print(inverted_data)
  77.  
  78. # {'world': ['b'], 'hello': ['a', 'c']}
  79.  
  80. print(inverted_data.get('hello'))
  81.  
  82. # ['a', 'c']
  83.  
  84. print(inverted_data.get('other'))
  85.  
  86. # None
  87.  
  88. # ----- example 5 -----
  89.  
  90. # invert dictionary using defaultdict - it doesn't lose element 'hello':'a'
  91.  
  92. from collections import defaultdict
  93.  
  94. inverted_data = defaultdict(list)
  95.  
  96. for key, val in data.items():
  97.     inverted_data[val].append(key)
  98.  
  99. print(inverted_data)
  100.  
  101. # defaultdict(<class 'list'>, {'world': ['b'], 'hello': ['a', 'c']})
  102.  
  103. print(inverted_data.get('hello'))
  104.  
  105. # ['a', 'c']
  106.  
  107. print(inverted_data.get('other'))
  108.  
  109. # None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement