python - Python:如何使用包含范围的 dict 加载 json
问题描述
我的 python 代码是关于从 dict 键生成序列号,并且我的 dict 键是使用模块中的cycle
包定义的范围。itertools
working example:
from itertools import cycle
e = {'Apple': cycle(range(1,999)),'Orange': cycle(range(1,999)),'Banana': cycle(range(1,999))}
def SequenceNum(f):
return f'{next(e[f])}'.zfill(3)
X = SequenceNum('Apple')
print(X)
output
001 --> it keeps incrementing in the range specified above in dict `e`
Challenge:
我的要求是将此字典e
转换为 json 文件。因此它将通过解析 json 文件来加载键和值。
cat test.json
{
"DATA": {
"Apple": "cycle(range(1,999))",
"Orange": "cycle(range(1,999))",
"Banana": "cycle(range(1,999))"
}
}
(我必须将 dict 值放在双引号内以避免 json 文件加载错误。)
code
import json
from itertools import cycle
with open('test.json') as f:
FromJson = json.load(f)
d = FromJson['DATA']
print(d)
def SequenceNum(f):
return f'{next(d[f])}'.zfill(3)
X = SequenceNum('Apple')
i = 1
while i <= 10:
print(i, SequenceNum('Apple'))
i += 1
这里新的 dict 是d
加载 json 文件,它将加载单引号中的值。
output
{'Apple': 'cycle(range(1,999))', 'Orange': 'cycle(range(1,999))', 'Banana': 'cycle(range(1,999))'} #THIS IS OUTPUT of 'd' after loading json file
Traceback (most recent call last):
File "c:\Users\chandu\Documents\test.py", line 14, in <module>
print(i, SequenceNum('Apple'))
File "c:\Users\chandu\Documents\test.py", line 12, in SequenceNum
return f'{next(d[f])}'.zfill(3)
TypeError: 'str' object is not an iterator
它给出了错误,因为我的 dict 值不能通过循环 itertools 模块正确迭代,因为它们在引号中。我不知道这个错误是否还有其他原因。
请帮助解决此错误,
提前致谢。
解决方案
如果您确定每个值是什么,则可以eval
小心操作:
def SequenceNum(f):
return f'{next(eval(d[f]))}'.zfill(3)
请注意,这是非常危险的使用,因为eval
评估任何传递给它并可能造成伤害的东西。
这也将始终从迭代器中获取第一个值,因为它每次都被评估为新值。要解决,您可以:
def SequenceNum(f):
return eval(d[f])
i = 1
seq_iter = SequenceNum('Apple')
while i <= 10:
print(i, f'{next(seq_iter)}'.zfill(3))
i += 1
推荐阅读
- java - 如何在 2 个片段之间传递值?
- terraform - 从地图列表创建重组地图
- javascript - 编写这个 Javascript 函数的更简洁的方法
- sql - SQL CASE WHEN 在等号左边?
- android - 已删除的 API 数据未反映在 android 应用程序中
- javascript - 在 useState 使用 eventListener keyup 改变 refs 后持久化值的问题
- typescript - 将 Interface 或 Type 的所有属性扩展为可能为 null
- ajax - 如何将 HTML 输入类型 =“文件”转换为八位字节流
- sql - SQL 替换数字
- docker - Docker 撰写问题