【问题标题】:What is the fastest way to iterate through a dictionary's value in python?在python中迭代字典值的最快方法是什么?
【发布时间】:2018-01-25 03:24:27
【问题描述】:

所以,我想知道迭代字典值并将其值与另一个变量进行比较的最快方法是什么。我有一个非常简单的特定字典结构:

"data": [
    {
     "id": "xxxxxxxxxxxxx"
    },
    {
     "id": "xxxxxxxxxxxxx"
    },
    {
     "id": "xxxxxxxxxxxxx"
    },
    {
     "id": "xxxxxxxxxxxxx"
    },
    {
     "id": "xxxxxxxxxxxxx"
    },
    {
     "id": "xxxxxxxxxxxxx"
    }
]

我已经遍历some_dict['data'],然后使用此代码比较它的['id'] 值:

for item in some_dict:
    if item['id'] == some_value:
        #do stuff

但是对于一个大尺寸的字典,这需要很多时间,所以我很好奇其他方法来做我想做的事。我听说 set 对大型列表迭代很有用,但无论如何可以从我的 dict 结构中使用它?

【问题讨论】:

    标签: json python-3.x loops dictionary


    【解决方案1】:

    在我看来,你的方式没问题。但如果你坚持不同的方式,那么你可以这样做:

    from itertools import chain
    flat_list = list(chain.from_iterable([d.values() for d in some_dict['data']]))
    for item in flat_list:
        if item == some_value:
            # do stuff
    

    或者,如果您只想检查是否存在:

    if some_value in flat_list:
        # do stuff
    

    关于set,如果id的值有重复,则会剔除。所以除非你没问题,否则我不会使用它。

    【讨论】:

    • 它实际上是唯一的 ID,所以 set 根本不会打扰我。并且使用chainset 会使过程更快,或者“从字典到链/集”部分会使其无用吗?
    • 这取决于您的字典列表的大小。如果它是“正常的”(最多 100 个条目左右),那么效果是微不足道的。如果它是一个巨大的列表(超过 10000 个条目),那么我想你会开始注意到一些延迟。但即便如此,它也不应该太糟糕。你可以这样想:迭代然后取消引用还是展平然后迭代?请注意,dictionary 获取项目的 摊销最坏情况O(n),而列表的相同操作是 O(1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2017-03-28
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多