Python 存储字典路径并读回

标签 python python-3.x

我正在遍历大量嵌套的列表字典(系统信息)并以这种格式存储键的完整路径:

.children[0].children[9].children[0].children[0].handle = PCI:0000:01:00.0
.children[0].children[9].children[0].children[0].description = Non-Volatile memory controller
.children[0].children[9].children[0].children[0].product = Samsung Electronics Co Ltd
.children[0].children[9].product = Xeon E7 v4/Xeon E5 v4/Xeon E3 v4/Xeon D DMI2
.children[2].product = PWS-406P-1R

接下来,完整的路径被读入并将与系统信息(数据)进行比较。如何将完整路径转换为这种格式?

Data['children'][0]['children'][9]['children'][0]['children'][0]['handle']
Data['children'][0]['children'][9]['product]'
Data['children'][2]['product']

我可以这样做:

data = re.findall(r"\.([a-z]+)\[(\d+)\]", key, re.IGNORECASE)

[('children', '0'), ('children', '9'), ('children', '0'), ('children', '0')]
[('children', '0'), ('children', '9'), ('children', '0'), ('children', '0')]
[('children', '0'), ('children', '9'), ('children', '0'), ('children', '0')]
[('children', '0'), ('children', '9')]
[('children', '2')]

我如何转换这些元组列表之一才能做到:

if Data['children'][2]['product'] == expected:
    print('pass')

最佳答案

您可以使用 itertoolsfunctoolsoperator 库将索引链接在一起并递归查找它们以获得最终值.

首先,我认为您应该更改正则表达式以获取最后一个 getter(即 handle、description、product)

re.findall(r"\.([a-z]+)(?:\[(\d+)\])?", key, re.IGNORECASE)

那应该给你这个

[('children', '0'), ('children', '9'), ('product', '')]

然后你可以做这样的事情来链接查找

import operator
import functools
import itertools

indexes = [('children', '0'), ('children', '9'), ('product', '')]

# This turns the list above into a flat list ['children', 0, 'children', ...]
# It also converts number strings to integers and excludes empty strings.
keys = (int(k) if k.isdigit() else k for k in itertools.chain(*indexes) if k)

# functools.reduce recursively looks up the keys
# operator.getitem() is a functional version of Data[key] == getitem(Data, key)
value = functools.reduce(operator.getitem, keys, Data)
if value == expected:
    pass

关于Python 存储字典路径并读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49782530/

相关文章:

python - hadoop 中的拆分和映射任务数

python - 我们可以在 Beautifulsoup 中将所有 XML 标签转换为小写吗

python - python中将edgelist导入igraph的格式

python - 将字典转换为方阵

python - 无法去除透明度,PIL getbbox() 和 Numpy 都不起作用

python - 计算 pandas 数据帧的总和

python - Pandas DataFrame 中的多步聚合

python - 我们如何在循环中创建 selenium webdriver 对象并在循环结束后关闭窗口?

python - 将 Cassandra OrderedMapSerializedKey 转换为 Python 字典

python - <类 'pandas.indexes.numeric.Int64Index'> 的类型错误 : cannot do slice indexing on <class 'tuple' > with these indexers [(2, )]