Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data = {
- 'a': 'hello',
- 'b': 'world',
- 'c': 'hello'
- }
- # ----- example 1 -----
- # invert dictionary - it loses element 'hello':'a'
- inverted_data = {val: key for key, val in data.items()}
- print(inverted_data)
- # {'hello': 'c', 'world': 'b'}
- print(inverted_data.get("hello"))
- # 'c'
- print(inverted_data.get("other"))
- # None
- # ----- example 2 -----
- # find all keys using "list comprehension"
- result = [key for key, val in data.items() if val == "hello"]
- print(result)
- # ['a', 'c']
- result = [key for key, val in data.items() if val == "other"]
- print(result)
- # [] # empty list
- # --- example 3 ---
- # find all keys using "for" loop
- result = []
- for key, val in data.items():
- if val == "hello":
- result.append(key)
- print(result)
- # ['a', 'c']
- result = []
- for key, val in data.items():
- if val == "other":
- result.append(key)
- print(result)
- # [] # empty list
- # ----- example 4 -----
- # invert dictionary using list as elements - it doesn't lose element 'hello':'a'
- inverted_data = dict()
- for key, val in data.items():
- if val not in inverted_data:
- inverted_data[val] = []
- inverted_data[val].append(key)
- print(inverted_data)
- # {'world': ['b'], 'hello': ['a', 'c']}
- print(inverted_data.get('hello'))
- # ['a', 'c']
- print(inverted_data.get('other'))
- # None
- # ----- example 5 -----
- # invert dictionary using defaultdict - it doesn't lose element 'hello':'a'
- from collections import defaultdict
- inverted_data = defaultdict(list)
- for key, val in data.items():
- inverted_data[val].append(key)
- print(inverted_data)
- # defaultdict(<class 'list'>, {'world': ['b'], 'hello': ['a', 'c']})
- print(inverted_data.get('hello'))
- # ['a', 'c']
- print(inverted_data.get('other'))
- # None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement