首页 > 解决方案 > 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 模块正确迭代,因为它们在引号中。我不知道这个错误是否还有其他原因。

请帮助解决此错误,

提前致谢。

标签: pythonjson

解决方案


如果您确定每个值是什么,则可以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

推荐阅读