hutool.core.map

字典工具类,对应 Java cn.hutool.core.map.MapUtil / BiMap / MapWrapper。

包含: - MapUtil : 静态工具方法集合 - MapWrapper : MutableMapping 包装基类 - BiMap : 双向字典(键↔值) - FuncKeyDict : 自定义键函数字典 - DictUtil : 字典工具方法集合(兼容旧接口)

Module Contents

Classes

MapUtil

Map工具类,对应 Java cn.hutool.core.map.MapUtil

MapWrapper

字典包装类,通过包装一个已有字典实现特定功能。

BiMap

双向Map,维护两个字典实现正向和反向查找。

FuncKeyDict

自定义函数Key风格的字典。

DictUtil

字典相关工具类。

Data

API

hutool.core.map.__all__ = ['BiMap', 'DictUtil', 'FuncKeyDict', 'MapUtil', 'MapWrapper']
hutool.core.map._K = 'TypeVar(...)'
hutool.core.map._V = 'TypeVar(...)'
hutool.core.map._DEFAULT_PARAM = 'DefaultParam(...)'
class hutool.core.map.MapUtil

Map工具类,对应 Java cn.hutool.core.map.MapUtil

static is_empty(m: dict) bool

字典是否为空。

参数:

m – 字典

返回:

是否为空

static is_not_empty(m: dict) bool

字典是否为非空。

参数:

m – 字典

返回:

是否为非空

static new_hash_map(*args, **kwargs) dict

新建 HashMap(Python dict)。

返回:

新字典

static new_linked_hash_map(*args, **kwargs) collections.OrderedDict

新建 LinkedHashMap(有序字典)。

返回:

新有序字典

static of(key, value) dict

创建单键值对字典

参数:
  • key – 键

  • value – 值

返回:

单键值对字典

static of_entries(*entries) dict

通过键值对元组创建字典

参数:

entries – (key, value) 元组序列

返回:

字典

static of_array(array: list) dict

通过数组创建字典,如 [k1, v1, k2, v2, …]

参数:

array – 交替排列的键值列表,长度必须为偶数

返回:

字典

static create_map(map_type: Optional[Type] = None) dict

根据类型创建字典实例

参数:

map_type – 字典类型

返回:

字典实例

static to_list_map(dict_list: Sequence[Dict[hutool.core.map._K, hutool.core.map._V]]) Dict[hutool.core.map._K, List[hutool.core.map._V]]

行转列,合并相同的键,值合并为列表

例如: [{‘a’:1,’b’:1}, {‘a’:2,’b’:2}] -> {‘a’:[1,2], ‘b’:[1,2]}

参数:

dict_list – 字典列表

返回:

键到列表的映射

static to_dict_list(list_dict: Dict[hutool.core.map._K, Sequence[hutool.core.map._V]]) List[Dict[hutool.core.map._K, hutool.core.map._V]]

列转行

例如: {‘a’:[1,2], ‘b’:[1,2]} -> [{‘a’:1,’b’:1}, {‘a’:2,’b’:2}]

参数:

list_dict – 键到列表的映射

返回:

字典列表

static join(m: dict, separator: str = '&', kv_separator: str = '=') str

字典转字符串连接

参数:
  • m – 字典

  • separator – 键值对之间的分隔符

  • kv_separator – 键与值之间的分隔符

返回:

连接后的字符串

static sort_join(params: dict, separator: str = '&', kv_separator: str = '=') str

字典按键排序后转字符串连接

参数:
  • params – 字典

  • separator – 键值对之间的分隔符

  • kv_separator – 键与值之间的分隔符

返回:

排序后连接的字符串

static filter(m: dict, *keys) dict

保留指定key的键值对,返回新字典

参数:
  • m – 字典

  • keys – 要保留的键

返回:

新字典

static filter_by_func(m: dict, filter_func: Callable) dict

按条件过滤字典

filter_func 接收 (key, value) 参数,返回 True 保留。

参数:
  • m – 字典

  • filter_func – 过滤函数 (key, value) -> bool

返回:

过滤后的新字典

static map_values(m: dict, map_func: Callable) dict

映射所有值

参数:
  • m – 字典

  • map_func – 映射函数 value -> new_value

返回:

值映射后的新字典

static sort(m: dict) collections.OrderedDict

按键排序,返回新OrderedDict

参数:

m – 字典

返回:

排序后的有序字典

static sort_by_value(m: dict, reverse: bool = False) collections.OrderedDict

按值排序

参数:
  • m – 字典

  • reverse – 是否降序

返回:

排序后的有序字典

static inverse(m: dict) dict

键值互换

互换键值对不检查值是否有重复,后加入的元素替换先加入的元素。

参数:

m – 字典

返回:

键值互换后的字典

static remove_any(m: dict, *keys) dict

移除指定key,返回新字典

参数:
  • m – 字典

  • keys – 要移除的键

返回:

移除后的新字典

static empty_if_null(m: Optional[dict]) dict

None转空字典

参数:

m – 字典,可能为None

返回:

原字典或空字典

static default_if_empty(m: dict, default: dict) dict

如果为空返回默认

参数:
  • m – 字典

  • default – 默认字典

返回:

非空的原字典或默认字典

static get_str(m: dict, key: str, default: str = '') str

获取字符串值

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

字符串值

static get_int(m: dict, key: str, default: int = 0) int

获取int值

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

int值

static get_float(m: dict, key: str, default: float = 0.0) float

获取float值

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

float值

static get_bool(m: dict, key: str, default: bool = False) bool

获取bool值

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

bool值

static get(m: dict, key: str, default=None, cast_type=None) Any

获取值,可选类型转换

参数:
  • m – 字典

  • key – 键

  • default – 默认值

  • cast_type – 类型转换函数(如 int, float, str)

返回:

转换后的值

static get_first_not_null(m: dict, *keys) Any

获取第一个非None的值

参数:
  • m – 字典

  • keys – 候选键

返回:

第一个非None的值,或None

static get_ignore_case(m: dict, key: str, default=None) Any

忽略大小写获取字典中的值。

遍历字典的键,找到第一个与 key 大小写不敏感匹配的键并返回其值。 仅适用于键为字符串的字典。

参数:
  • m – 字典

  • key – 键(字符串)

  • default – 默认值

返回:

匹配到的值,未找到返回默认值

>>> MapUtil.get_ignore_case({"Name": "Alice", "AGE": 20}, "name")
'Alice'
>>> MapUtil.get_ignore_case({"Name": "Alice"}, "age", 0)
0
static group_by_field(dict_list: Sequence[Dict[hutool.core.map._K, hutool.core.map._V]], field_key: hutool.core.map._K) Dict[hutool.core.map._V, List[Dict[hutool.core.map._K, hutool.core.map._V]]]

按字段分组

参数:
  • dict_list – 字典列表

  • field_key – 分组依据的键

返回:

分组后的字典

static flat(m: dict) List

将字典展开为列表 [k1, v1, k2, v2, …]

参数:

m – 字典

返回:

展开后的列表

static is_sub_map(sub: dict, full: dict) bool

判断sub是否为full的子集

参数:
  • sub – 子字典

  • full – 完整字典

返回:

是否为子集

static contains_key(m: dict, key: Any) bool

字典是否包含指定键

参数:
  • m – 字典

  • key – 键

返回:

是否包含

static contains_value(m: dict, value: Any) bool

字典是否包含指定值

参数:
  • m – 字典

  • value – 值

返回:

是否包含

static top_n_keys(m: dict, n: int) list

获取字典中值最大的前 N 个键。

按值从大到小排序后返回前 N 个键。

参数:
  • m – 字典

  • n – 返回的键数量

返回:

值最大的前 N 个键的列表

>>> MapUtil.top_n_keys({'a': 3, 'b': 1, 'c': 5, 'd': 2}, 2)
['c', 'a']
static merge(m1: dict, m2: dict) dict

合并两个字典,返回新字典(m2 覆盖 m1)

参数:
  • m1 – 第一个字典

  • m2 – 第二个字典(优先级更高)

返回:

合并后的新字典

static to_camel_case_map(m: dict) dict

将字典的键转换为驼峰命名。

参数:

m – 原字典(键为 snake_case 字符串)

返回:

键为 camelCase 的新字典

static to_object_array(m: dict) list

将字典转为二维数组 [[key, value], …]。

参数:

m – 字典

返回:

二维数组

static join_ignore_null(m: dict, separator: str = '&', kv_sep: str = '=') str

将字典拼接为查询字符串,忽略值为 None 的条目。

参数:
  • m – 字典

  • separator – 键值对分隔符

  • kv_sep – 键值分隔符

返回:

拼接后的字符串

static edit(m: dict, func: Callable) dict

对字典的每个值应用函数。

参数:
  • m – 原字典

  • func – 值转换函数,接收 (key, value) 参数

返回:

新字典

static map_(m: dict, key_func=None, value_func=None) dict

对字典的键和/或值进行映射。

参数:
  • m – 原字典

  • key_func – 键映射函数

  • value_func – 值映射函数

返回:

映射后的新字典

static reverse(m: dict) dict

反转字典(值做键,键做值),值重复时后者覆盖。

参数:

m – 原字典

返回:

反转后的字典

static rename_key(m: dict, old_key: Any, new_key: Any) dict

重命名字典的键。

参数:
  • m – 原字典(会被修改)

  • old_key – 旧键

  • new_key – 新键

返回:

修改后的字典

static remove_null_value(m: dict) dict

移除值为 None 的条目。

参数:

m – 原字典(会被修改)

返回:

修改后的字典

static remove_by_value(m: dict, value: Any) dict

移除指定值的所有条目。

参数:
  • m – 原字典(会被修改)

  • value – 要移除的值

返回:

修改后的字典

static remove_if(m: dict, predicate: Callable) dict

按条件移除条目。

参数:
  • m – 原字典(会被修改)

  • predicate – 条件函数,接收 (key, value),返回 True 表示移除

返回:

修改后的字典

static get_any(m: dict, *keys: Any) Any

按顺序查找第一个存在的键并返回其值。

参数:
  • m – 字典

  • keys – 多个键

返回:

第一个存在的键对应的值,都不存在返回 None

static get_double(m: dict, key: Any, default: float = 0.0) float

获取 double 类型的值。

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

float 值

static get_long(m: dict, key: Any, default: int = 0) int

获取 long 类型的值。

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

int 值

static get_date(m: dict, key: Any, default=None)

获取日期类型的值。

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

值(不做转换,直接返回)

static entry(key: Any, value: Any) dict

创建单键值对字典。

参数:
  • key – 键

  • value – 值

返回:

单键值对字典

static compute_if_absent(m: dict, key: Any, func: Callable) Any

如果键不存在,则计算并添加值。

参数:
  • m – 字典(会被修改)

  • key – 键

  • func – 值计算函数(接收 key 参数)

返回:

static partition(m: dict, size: int) List[dict]

将字典按大小分割为多个子字典。

参数:
  • m – 字典

  • size – 每个子字典的最大条目数

返回:

子字典列表

static flatten(m: dict, prefix: str = '', separator: str = '.') dict

将嵌套字典扁平化。

参数:
  • m – 嵌套字典

  • prefix – 键前缀

  • separator – 键分隔符

返回:

扁平化后的字典

static values_of_keys(m: dict, keys: Iterable) list

获取字典中指定键的值列表。

参数:
  • m – 字典

  • keys – 键列表

返回:

值列表

static new_tree_map() collections.OrderedDict

创建有序字典(TreeMap 等价)。

返回:

OrderedDict 实例

static new_identity_map() dict

创建 IdentityMap(使用 id() 做键的字典)。

注意:返回普通 dict,调用方需使用 id(obj) 做键。

返回:

空字典

static new_concurrent_hash_map() dict

创建线程安全字典。

Python 的 dict 本身在 CPython 中是线程安全的(GIL 保护)。 此方法返回普通 dict,如需严格线程安全请使用 threading.Lock。

返回:

空字典

static wrap(m: dict) dict

包装字典为不可修改视图。

参数:

m – 原字典

返回:

包装后的字典(types.MappingProxyType)

static unmodifiable(m: dict) dict

返回不可修改的字典视图。

参数:

m – 原字典

返回:

不可修改的映射

static get_short(m: dict, key: str, default: int = 0) int

获取 short 值(Python 中等同于 int)。

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

int 值

static get_char(m: dict, key: str, default: str = '') str

获取 char 值(Python 中为单字符字符串)。

参数:
  • m – 字典

  • key – 键

  • default – 默认值

返回:

单字符字符串

static empty() dict

返回空字典。

返回:

空字典

static split_by_size(data: dict, size: int) list

按大小分割字典为多个子字典。

参数:
  • data – 原字典

  • size – 每个子字典的最大大小

返回:

子字典列表

static sort_by_key(data: dict, reverse: bool = False) dict

按 key 排序字典,返回 OrderedDict。

参数:
  • data – 原字典

  • reverse – 是否倒序

返回:

排序后的字典

class hutool.core.map.MapWrapper(data: Optional[Dict[hutool.core.map._K, hutool.core.map._V]] = None, /, **kwargs)

Bases: collections.OrderedDict

字典包装类,通过包装一个已有字典实现特定功能。

对应 Java cn.hutool.core.map.MapWrapper。 继承 OrderedDict,可作为完整 dict 使用。

Initialization

Initialize self. See help(type(self)) for accurate signature.

classmethod __class_getitem__(item)
size() int

获取字典大小

返回:

字典大小

is_empty() bool

字典是否为空

返回:

字典是否为空

is_not_empty() bool

字典是否非空

返回:

字典是否非空

__repr__()
class hutool.core.map.BiMap(data: Optional[dict] = None, /, **kwargs)

Bases: hutool.core.map.MapWrapper[hutool.core.map._K, hutool.core.map._V]

双向Map,维护两个字典实现正向和反向查找。

对应 Java cn.hutool.core.map.BiMap。 互换键值对不检查值是否有重复,如果有则后加入的元素替换先加入的元素。

Initialization

初始化

参数:

data – 被包装的字典

_build_inverse() Dict[hutool.core.map._V, hutool.core.map._K]

构建反向字典

返回:

反向字典

_ensure_inverse() Dict[hutool.core.map._V, hutool.core.map._K]

确保反向字典已构建

返回:

反向字典

_invalidate_inverse() None

标记反向字典需要重建

__setitem__(key: hutool.core.map._K, value: hutool.core.map._V) None
__delitem__(key: hutool.core.map._K) None
update(__m=None, **kwargs: hutool.core.map._V) None

更新字典

参数:

__m – 字典或者有两个元素的可迭代对象

setdefault(key: hutool.core.map._K, default: hutool.core.map._V = None) hutool.core.map._V

添加默认值,如果存在键则不添加

参数:
  • key – 键

  • default – 默认值

返回:

pop(key: hutool.core.map._K, *args) hutool.core.map._V

弹出值

参数:

key – 键

返回:

popitem(last: bool = True) Tuple[hutool.core.map._K, hutool.core.map._V]

弹出键值对

返回:

键值对

clear() None
get(key: hutool.core.map._K, default=None) Optional[hutool.core.map._V]

获取值

参数:
  • key – 键

  • default – 默认值

返回:

get_key(value: hutool.core.map._V, default=None) Optional[hutool.core.map._K]

根据值获得键

参数:
  • value – 值

  • default – 默认值

返回:

get_inverse() Dict[hutool.core.map._V, hutool.core.map._K]

获取反向字典(值->键)

返回:

反向字典

reset_inverse() None

重置反转的字典

keys()

获取所有键。

返回:

键的视图

values()

获取所有值。

返回:

值的视图

items()

获取所有键值对。

返回:

键值对的视图

copy() hutool.core.map.BiMap[hutool.core.map._K, hutool.core.map._V]

浅拷贝

返回:

BiMap副本

__copy__() hutool.core.map.BiMap[hutool.core.map._K, hutool.core.map._V]
__repr__()
class hutool.core.map.FuncKeyDict(data: Optional[Dict[hutool.core.map._K, hutool.core.map._V]] = None, key_func: Optional[Callable[[hutool.core.map._K], hutool.core.map._K]] = None, /, **kwargs)

Bases: hutool.core.map.MapWrapper[hutool.core.map._K, hutool.core.map._V]

自定义函数Key风格的字典。

所有键在存入和读取时都会经过 key_func 处理,例如统一转小写。

Initialization

初始化

注意提供的字典中不能有键值对,否则可能导致自定义key失效。

参数:
  • data – 提供的字典

  • key_func – 自定义键函数

_transform_key(key: hutool.core.map._K) hutool.core.map._K

根据函数自定义键

参数:

key – 原始键

返回:

自定义后的键

__getitem__(key: hutool.core.map._K)
__setitem__(key: hutool.core.map._K, value: hutool.core.map._V)
__delitem__(key: hutool.core.map._K)
__contains__(key: hutool.core.map._K) bool
get(key: hutool.core.map._K, default=None)
pop(key: hutool.core.map._K, *args)
setdefault(key: hutool.core.map._K, default: hutool.core.map._V = None) hutool.core.map._V
property key_func: Optional[Callable[[hutool.core.map._K], hutool.core.map._K]]

获取键函数。

返回:

键函数

__repr__()
class hutool.core.map.DictUtil

Bases: hutool.core.map.MapUtil

字典相关工具类。

static empty_if_none(value: Union[dict, None]) dict

如果提供的集合为None, 返回一个空集合,否则返回原集合

参数:

value – 提供的集合,可能为None

返回:

原集合,若为None返回空集合

static new_dict(is_ordered: bool = False, /, *args, **kwargs) dict

新建一个字典

DictUtil.new_dict({‘a’: 1}, zip([‘b’], [2]), [(‘c’, 3)], d=4)

参数:

is_ordered – 字典的Key是否有序

返回:

字典

static create_dict(dict_type: Optional[Type] = None) dict

根据类型创建字典

参数:

dict_type – 字典类型

返回:

字典实例

static to_list_dict(dict_list: Sequence[Dict[hutool.core.map._K, hutool.core.map._V]]) Dict[hutool.core.map._K, List[hutool.core.map._V]]

行转列,合并相同的键,值合并为列表

传入: [{‘a’: 1, ‘b’: 1, ‘c’: 1}, {‘a’: 2, ‘b’: 2}, {‘a’: 3, ‘b’: 3}, {‘a’: 4}] 结果: {‘a’: [1,2,3,4], ‘b’: [1,2,3], ‘c’: [1]}

参数:

dict_list – 字典列表

返回:

字典