如何遍历多个json字典来检查同一类型键的值?

2024-04-28 11:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够在多个json字典中获得“delta”的值。我用的是kivy的JsonStore,如果有什么变化的话。当我按下启动check\u streak函数的按钮时,我得到NameError:name'delta'没有定义。代码如下:

class MainApp(App):

    def build(self): # build() returns an instance
        self.store = JsonStore("streak.json") # file that stores the streaks:


        return presentation

    def check_streak(self, instance):

        for item in self.store.find(delta):

            if delta > time.time():
                print("early")

            if delta == time.time():
                print("on time")

            if delta < time.time():
                print("late")

以下是单独文件中的json字典:

{"first": {"action": "first", "action_num": "1", "seconds": 60, "score": 0, "delta": 1555714261.0438898}, "second": {"action": "second", "action_num": "2", "seconds": 120, "score": 0, "delta": 1555879741.894656}}

我希望能够从文件中放入的每个对象中获取“delta”的值。我该怎么做?你知道吗


Tags: instancestorebuildselfjsonif字典time
3条回答

变量delta不存在,因此出现了错误。你知道吗

大概你是想for item in self.store.find("delta"):(用delta作为字符串)?你知道吗

我想你可以尝试这样的方法,其中ddself.store

In [10]: my_deltas = []

In [11]: for key in dd:
    ...:     my_deltas.append(dd[key].get('delta'))
    ...:

In [12]: my_deltas
Out[12]: [1555714261.0438898, 1555879741.894656]

这个问题可以通过项生成器来解决,以获得'delta'的值。代码如下:

class MainApp(App):

    def build(self): # build() returns an instance
        self.store = JsonStore("streak.json") # file that stores the streaks:


        return presentation

    # Gets the value of delta (code I may never understand lol)
    def item_generator(self, json_input, lookup_key):
        if isinstance(json_input, dict):
            for k, v in json_input.items():
                if k == lookup_key:
                    yield v
                else:
                    yield from self.item_generator(v, lookup_key)
        elif isinstance(json_input, list):
            for item in json_input:
                yield from self.item_generator(item, lookup_key)

    def check_streak(self, instance):
        with open("streak.json", "r") as read_file:
            data = json.load(read_file)
            values = self.item_generator(data, 'delta')



        for honey in values:
            if honey > time.time():
                print("early")

            if honey == time.time():
                print("on time")

            if honey < time.time():
                print("late")

相关问题 更多 >