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。



目录
相关文章
|
2天前
|
机器学习/深度学习 人工智能 算法
Python在计算机视觉(CV)中扮演重要角色,得益于其丰富的库如OpenCV、Pillow和Scikit-image。
【7月更文挑战第5天】Python在计算机视觉(CV)中扮演重要角色,得益于其丰富的库如OpenCV、Pillow和Scikit-image。CV涉及图像处理、模式识别和机器学习,用于图像理解和生成。Python的跨平台特性和活跃社区使其成为CV的理想工具。基本流程包括图像获取、预处理、特征提取、分类识别及图像生成。例如,面部识别通过预处理图像,使用如`cv2.CascadeClassifier`进行检测;物体检测类似,但需适应不同目标;图像生成则利用GAN创造新图像。
17 4
|
2天前
|
存储 Python
python将字典的键或值解包到变量中
【7月更文挑战第5天】
12 4
|
22小时前
|
Java 测试技术 开发者
Python:使用标准库编写单元测试
在现代软件开发中,编写单元测试是确保代码质量和可靠性的重要步骤。Python 提供了一个内置的单元测试框架,称为 unittest,它可以帮助开发者方便地编写和运行测试。本文将详细介绍如何使用 unittest 编写单元测试。
|
2天前
|
Python
|
3天前
|
Python
Python中字典 直接解包
【7月更文挑战第4天】
10 3
|
2天前
|
Python
python解包字典到函数参数
【7月更文挑战第5天】
6 2
|
3天前
|
Python
Python中字典解包使用*和**操作符
【7月更文挑战第4天】
9 3
|
2天前
|
数据可视化 数据挖掘 API
数据可视化秘籍聚焦Python的Matplotlib和Seaborn库,它们是数据分析的得力工具。
【7月更文挑战第5天】数据可视化秘籍聚焦Python的Matplotlib和Seaborn库,它们是数据分析的得力工具。Matplotlib是基础库,提供高度自定义的2D图表,而Seaborn在其上构建,提供美观的统计图形。文章介绍了如何用两者画线图、散点图、条形图、饼图和直方图,展示数据趋势和关系。
|
2天前
|
Python
python解包字典到新的字典
【7月更文挑战第5天】
10 1
|
3天前
|
Python
Python中字典解包解包到变量
【7月更文挑战第4天】
9 1