【发布时间】:2020-04-13 11:24:35
【问题描述】:
我的 python 代码是关于从 dict 键生成序列号,并且我的 dict 键是使用 itertools 模块中的 cycle 包定义的范围。
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文件来加载key和value。
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 模块正确迭代,因为它们在引号中。我不知道这个错误是否还有其他原因。
请帮忙解决这个错误,
提前致谢。
【问题讨论】:
-
所以您添加了引号,但甚至没有尝试任何操作来撤消该更改?
-
嗨,斯科特,如果我删除 json 文件中 dict 值的引号,它会在加载 json 文件时出错。可能是反对 json 数据格式。