【问题标题】:Python: how to load json with dict containing rangePython:如何使用包含范围的 dict 加载 json
【发布时间】: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 数据格式。

标签: python json


【解决方案1】:

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

【讨论】:

  • 嗨,奥斯汀,感谢您的回复..使用eval 后,迭代器错误得到解决..但我无法正确使用循环(范围(1,999)),因为它每次出现时都会打印 001 ..
  • 我已经用一个while循环更新了我的问题。在工作示例中,它会打印 001、002、003..直到 010...,而在 json 示例(使用 eval)中,它会继续打印 001,并且不会从其范围内增加值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-26
  • 2013-04-20
  • 2015-06-18
  • 2010-10-05
  • 1970-01-01
  • 2014-11-27
相关资源
最近更新 更多