python字典分类
时间: 2023-07-01 12:21:40 浏览: 87
Python中的字典分类可以通过字典推导式来实现。具体的方法是根据字典中某个键的值来分组,例如:
```python
data = [
{"name": "Alice", "age": 20, "gender": "Female"},
{"name": "Bob", "age": 25, "gender": "Male"},
{"name": "Charlie", "age": 30, "gender": "Male"},
{"name": "David", "age": 35, "gender": "Male"},
{"name": "Eve", "age": 40, "gender": "Female"},
]
# 根据性别将字典分类
female_data = [d for d in data if d["gender"] == "Female"]
male_data = [d for d in data if d["gender"] == "Male"]
print(female_data) # [{'name': 'Alice', 'age': 20, 'gender': 'Female'}, {'name': 'Eve', 'age': 40, 'gender': 'Female'}]
print(male_data) # [{'name': 'Bob', 'age': 25, 'gender': 'Male'}, {'name': 'Charlie', 'age': 30, 'gender': 'Male'}, {'name': 'David', 'age': 35, 'gender': 'Male'}]
```
在上面的例子中,我们根据字典中的`gender`键将字典分类为`female_data`和`male_data`两个小字典。您可以根据自己的需求来选择分类的方式和键名。
阅读全文