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。



目录
打赏
0
0
0
0
74
分享
相关文章
通义灵码 Rules 库合集来了,覆盖Java、TypeScript、Python、Go、JavaScript 等
通义灵码新上的外挂 Project Rules 获得了开发者的一致好评:最小成本适配我的开发风格、相当把团队经验沉淀下来,是个很好功能……
922 103
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
247 20
解决Python requests库POST请求参数顺序问题的方法。
总之,想要在Python的requests库里保持POST参数顺序,你要像捋顺头发一样捋顺它们,在向服务器炫耀你那有条不紊的数据前。抓紧手中的 `OrderedDict`与 `json`这两把钥匙,就能向服务端展示你的请求参数就像经过高端配置的快递包裹,里面的商品摆放井井有条,任何时候开箱都是一种享受。
57 10
|
1月前
|
分析参数顺序对Python requests库进行POST请求的影响。
最后,尽管理论上参数顺序对POST请求没影响,但编写代码时仍然建议遵循一定的顺序和规范,比如URL总是放在第一位,随后是data或json,最后是headers,这样可以提高代码的可读性和维护性。在处理复杂的请求时,一致的参数顺序有助于调试和团队协作。
95 9
Python 中的 `and`, `or`, `not` 运算符
本文介绍了 Python 中的逻辑运算符 `and`、`or` 和 `not` 的基本用法及其特性。这些运算符主要用于布尔运算,特别是在条件判断和循环中非常有用。文章详细解释了每个运算符的功能,例如 `and` 检查所有表达式是否为真,`or` 检查是否有任意一个表达式为真,`not` 用于取反。此外,还提到这些运算符支持短路特性,并可应用于非布尔值场景。掌握这些运算符有助于编写更高效、简洁的代码。
231 11
Python数据结构:列表、元组、字典、集合
Python 中的列表、元组、字典和集合是常用数据结构。列表(List)是有序可变集合,支持增删改查操作;元组(Tuple)与列表类似但不可变,适合存储固定数据;字典(Dictionary)以键值对形式存储,无序可变,便于快速查找和修改;集合(Set)为无序不重复集合,支持高效集合运算如并集、交集等。根据需求选择合适的数据结构,可提升代码效率与可读性。
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
249 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
156 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
7月前
|
Python的标准库
Python的标准库
278 77

推荐镜像

更多
登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问