1. Dict: Magic of key-value pairs
1. Basic usage (create and access)
person = {"name": "Alice", "age": 25, "city": "Shanghai"} print(person["name"]) #Output: Alice
2. Efficient search of dictionaries
The search speed of the dictionary is extremely fast, with a time complexity of O(1). Compared with O(n) of list, the advantages are obvious when processing large amounts of data.
3. Dictionary derivation
squares = {x: x*x for x in range(1, 6)} print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
4. get() method, elegantly handle KeyError
person = {"name": "Alice", "age": 25} score = ("score", 0) print(score) # Output: 0
5. Correct posture for merging dictionary
a = {"x": 1, "y": 2} b = {"y": 3, "z": 4} c = {**a, **b} print(c) # Output: {'x': 1, 'y': 3, 'z': 4}
6. Things to note
- dict (dictionary) does not allow a key to be created twice, but when creating a dict (dictionary), if a key value is assigned twice, the value assigned last time will be based on the value assigned to it.
- dict (Dictionary) keys must be immutable, but keys can be used as numbers, strings or tuples, but lists cannot be used
Functions and methods of (Dictionary)
Methods and functions | describe |
---|---|
len(dict) | Calculate the number of dictionary elements |
str(dict) | Output dictionary printable string representation |
type(variable) | Returns the input variable type, if the variable is a dictionary, it returns the dictionary type |
() | Delete all elements in the dictionary |
() | Return a shallow copy of a dictionary |
() | Return all values in the dictionary as a list |
popitem() | Randomly return and delete a pair of keys and values in the dictionary |
() | Returns a traversable array of (keys, values) tuples as a list |
2. Set (set): a tool for deduplication and efficient calculation
1. Basic usage (create)
set1=set([123,456,789]) print(set1) fruits = {"apple", "banana", "orange"} ("pear") print(fruits)
2. Set to remove heavy weight
nums = [1, 2, 2, 3, 4, 4, 5] unique_nums = set(nums) print(unique_nums) # Output: {1, 2, 3, 4, 5}
3. Efficient operation of collections
- Intersection:
&
- Union:
|
- Differences:
-
a = {1, 2, 3} b = {2, 3, 4} print(a & b) # Output: {2, 3}print(a | b) # Output: {1, 2, 3, 4}print(a - b) # Output: {1}
4. Set derivation
even = {x for x in range(10) if x % 2 == 0} print(even) # Output: {0, 2, 4, 6, 8}
3. Summary
DictSuitable for storage mapping relationships, extremely fast search speed
SetSuitable for deduplication and set operations, high efficiency
Master derivation, merging, deduplication and other techniques to make your code more Pythonic!
This is the article about the practical skills you must know about Python Dict and Set. For more information about Python Dict and Set skills, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!