# Dictionary with initial key-value pairsfilled_dict = {'key1': 'value1', 'key2': 'value2'}
# Using dict() constructorconstructed_dict =dict(key1='value1', key2='value2')
valueList=list(filled_dict.values())
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in my_dict.keys():
print(f"Key: {key}")
LC 49
defaultdict
defaultdict(int) is more suitable for general scenarios where a default value is needed when a key does not exist, not necessarily just for counting.
1
2
3
dd = defaultdict(int) # int type, default value is 0dd = defaultdict(lambda: 'default_value')
defaultdict(lambda: [0, 0]) # key is an array
Counter
Counter is more suitable for frequency statistics and occurrence analysis of iterables. Its built-in counting methods can simplify many scenarios. Counter(p) means creating a counter from an iterable.
del cnt[x] deletes the count for x. len(cnt) gets the number of elements counted.
Create a new Counter
1
collections.Counter(nums)
list
index()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
numbers = [1, 2, 3, 4, 5]
# Find the position of number 3position = numbers.index(3)
print(position) # Output: 2# Find number 3 between index 1 and 4position = numbers.index(3, 1, 4)
print(position) # Output: 2# Try to find a non-existent numbertry:
position = numbers.index(7)
exceptValueErroras e:
print("Not found") # Output: Not found
sort()
It sorts the list in place and does not create a new list. It can only be applied to lists.
String comparison
Independent of length
1
print("apple"<"apricot") # False
iterable
Iterable: list, tuple, str, dict, set, range, enumerate, map
sorted(iterable) returns a new sorted list. The original iterable is not modified. Time complexity is O(nlogn)