python 一个点运算符操作的字典库:DottedDict

简介: python 一个点运算符操作的字典库:DottedDict

DottedDict 是一种特殊的数据结构,它结合了字典(Dictionary)和点符号(Dot Notation)访问的优点,为用户提供了一种更加直观和方便的方式来处理和访问嵌套的数据。在这篇文章中,我们将深入探讨 DottedDict 的概念、实现方式、使用场景以及它在数据处理中的优势。

什么是 DottedDict?

DottedDict 是一种允许用户通过点符号来访问嵌套键值对的数据结构。在传统的字典中,如果需要访问一个嵌套的值,用户通常需要通过键来逐层访问,例如 data['outer_key']['inner_key']。而使用 DottedDict,用户可以直接通过点符号来访问,如 data.outer_key.inner_key,这种方式更加直观和易于理解。

DottedDict 的安装

C:\Users>pip install dotteddict
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting dotteddict
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e5/80/2b0f5c84f4f56f96f4cb03470379b0f5827b68e75ec9df47b7d6497f6fad/dotteddict-2016.3.11.tar.gz (3.1 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: dotteddict
  Building wheel for dotteddict (setup.py) ... done
  Created wheel for dotteddict: filename=dotteddict-2016.3.11-py2.py3-none-any.whl size=3275 sha256=8905f8c47622a8c1149c24871afc1b77899d6bd19fc486807f90773a2ac688b6
  Stored in directory: c:\users\boyso\appdata\local\pip\cache\wheels\94\04\da\3e3aa22786fbbe407327f8d3da5580592217bdf16e4d2d9070
Successfully built dotteddict
Installing collected packages: dotteddict
Successfully installed dotteddict-2016.3.11
 

DottedDict 的实现方式

DottedDict 的实现通常依赖于面向对象编程中的属性访问机制。在 Python 中,可以通过定义一个类,并重载 _getattr__ 方法来实现 DottedDict 的行为。当用户尝试访问一个属性时,__getattr__ 方法会被调用,并在其中查找相应的键值对。如果找到了,就返回对应的值;如果没有找到,就抛出一个属性不存在的错误。

例如,以下是一个简单的 DottedDict 实现:

class DottedDict:
    def __init__(self, data):
        self._data = data
 
    def __getattr__(self, item):
        # 如果项是字典类型,则返回 DottedDict 对象以便继续使用点符号
        if isinstance(self._data.get(item), dict):
            return DottedDict(self._data.get(item))
        else:
            return self._data.get(item)
 
# 使用示例
data = DottedDict({'outer_key': {'inner_key': 'value'}})
print(data.outer_key.inner_key)  # 输出: value

DottedDict 的使用场景

DottedDict 在处理配置文件、解析 JSON 数据或者在任何需要处理嵌套数据的场景中都非常有用。例如,在配置文件中,经常会有多层的设置,使用 DottedDict 可以方便地读取和修改这些设置,而不需要编写复杂的访问函数。

DottedDict 的优势

  1. 直观性:通过点符号访问嵌套数据,使得代码更加易读和易于维护。
  2. 简洁性:减少了访问嵌套数据时所需的代码量,使得代码更加简洁。
  1. 灵活性:DottedDict 可以轻松地与其他数据结构结合使用,如列表和元组,提供了更多的数据处理可能性。
  2. 错误友好:当尝试访问不存在的键时,DottedDict 会抛出错误,这有助于及时发现和修复问题。

DottedDict 的基本用法

 |  For example:
 |
 |      data = {"people": {"bob": {"status": True}, "john": {"status": False}}}
 |      dotted = dotteddict(data)
 |      dotted.people.bob.status
 |      dotted["people.john.status"]
 |
 |  This is in contrast to using defaults:
 |
 |      dotted["people"]["john"]["status"]
 
创建对象

使用普通字典创建 DottedDict 对象:

from dotteddict import dotteddict
 
# 使用字典创建
data = dotteddict({"name": "Alice", "age": 30})
访问元素

使用点号访问 DottedDict 元素:

print(data.name) # 输出:Alice
print(data.age)  # 输出:30
修改元素

同样使用点号修改元素:

data.age = 31
print(data.age) # 输出:31
嵌套字典

DottedDict 支持嵌套字典,我们可以像访问对象属性一样访问嵌套元素:

data = DottedDict({"user": {"name": "Charlie", "age": 28}})
print(data.user.name)  # 输出:Charlie
print(data.user.age)   # 输出:28
其他操作

DottedDict 支持大部分字典操作,例如:

 |  clear(...)
 |      D.clear() -> None.  Remove all items from D.
 |
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items
 |
 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
 |
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |
 |      If the key is not found, return the default if given; otherwise,
 |      raise a KeyError.
 |
 |  popitem(self, /)
 |      Remove and return a (key, value) pair as a 2-tuple.
 |
 |      Pairs are returned in LIFO (last-in, first-out) order.
 |      Raises KeyError if the dict is empty.
 |
 |  setdefault(self, key, default=None, /)
 |      Insert key with a value of default if key is not in the dictionary.
 |
 |      Return the value for key if key is in the dictionary, else default.
 |
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 |      In either case, this is followed by: for k in F:  D[k] = F[k]
 |
 |  values(...)
 |      D.values() -> an object providing a view on D's values

使用实例

from dotteddict import dotteddict
 
# 假设我们有一个用户的嵌套信息字典
user_info = {
    "personal": {
        "name": "Charlie",
        "age": 28,
        "location": {
            "city": "San Francisco",
            "country": "USA"
        }
    },
    "contact": {
        "email": "charlie@example.com",
        "phone": "555-0199"
    },
    "preferences": {
        "language": "English",
        "theme": "Dark"
    }
}
 
# 使用 DottedDict 来包装这个嵌套字典
user = dotteddict(user_info)
 
# 现在我们可以方便地访问用户信息
print(f"User Name: {user.personal.name}")
print(f"Age: {user.personal.age}")
print(f"Location: {user.personal.location.city}, {user.personal.location.country}")
print(f"Email: {user.contact.email}")
print(f"Phone: {user.contact.phone}")
print(f"Preferred Language: {user.preferences.language}")
print(f"Theme: {user.preferences.theme}")
 
# 我们也可以修改用户信息
user.personal.age = 29
user.contact.phone = "555-0199-1234"
 
# 甚至可以添加新的嵌套信息
user.education = dotteddict({
    "highest_degree": "Master's",
    "field_of_study": "Computer Science"
})
 
# 展示修改和新增的信息
print(f"Age (updated): {user.personal.age}")
print(f"Phone (updated): {user.contact.phone}")
print("Education Info:")
print(f"Highest Degree: {user.education.highest_degree}")
print(f"Field of Study: {user.education.field_of_study}")

结论

DottedDict 是一种强大的数据结构,它通过提供点符号访问机制,极大地简化了处理嵌套数据的过程,让字典操作更加直观和优雅,让代码变得更加 pythonic。



目录
相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
751 2
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
2474 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
1253 0
|
传感器 运维 前端开发
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
本文解析异常(anomaly)与新颖性(novelty)检测的本质差异,结合distfit库演示基于概率密度拟合的单变量无监督异常检测方法,涵盖全局、上下文与集体离群值识别,助力构建高可解释性模型。
866 10
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
|
数据可视化 关系型数据库 MySQL
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
本文详解基于Python的电影TOP250数据可视化大屏开发全流程,涵盖爬虫、数据存储、分析及可视化。使用requests+BeautifulSoup爬取数据,pandas存入MySQL,pyecharts实现柱状图、饼图、词云图、散点图等多种图表,并通过Page组件拖拽布局组合成大屏,支持多种主题切换,附完整源码与视频讲解。
1206 4
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
730 3
|
JSON 网络安全 数据格式
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
1071 51
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
897 18
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
1250 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程

推荐镜像

更多