Dict
0 Basics
0.1 Index
Index can be any immutable type.
- Strings and numbers can always be keys.
- Lists cannot be keys.
- Tuples can be used as keys if they contain only strings, numbers, or tuples.
- If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.
1 Init
d = {'name': 'JJ', 'age': 20} # {'name': 'JJ', 'age': 20}
d = dict(name='JJ', age=20) # {'name': 'JJ', 'age': 20}
d = dict([('name', 'JJ'), ('age', 20)]) # {'name': 'JJ', 'age': 20}
d = dict(zip(['name', 'age'], ['JJ', 20])) # {'name': 'JJ', 'age': 20}
d = dict.fromkeys(['a', 'b']) # {'a': None, 'b': None}
d = dict.fromkeys(['a', 'b'], 1) # {'a': 1, 'b': 1}
d = {x: x**2 for x in (1, 2, 3)} # {1: 1, 2: 4, 3: 9}
2 C
3 R
d = dict.fromkeys(['b', 'a'], 1) # {'b': 1, 'a': 1}
# key: b value: 1
# key: a value: 1
for key in d:
print("key: %s value: %s" % (key, d[key]))
print(list(d)) # ['b', 'a']
print(sorted(d)) # ['a', 'b']
print('a' in d) # True
print('c' not in d) # True
4 U
5 D
d = dict.fromkeys(['a', 'b'], 1) # {'a': 1, 'b': 1}
del d['a'] # {'b': 1}