Python list of dictionaries search

后端 未结 21 2312
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:41

Assume I have this:

[
{\"name\": \"Tom\", \"age\": 10},
{\"name\": \"Mark\", \"age\": 5},
{\"name\": \"Pam\", \"age\": 7}
]

and by searchin

21条回答
  •  天涯浪人
    2020-11-22 10:15

    Here is a comparison using iterating throuhg list, using filter+lambda or refactoring(if needed or valid to your case) your code to dict of dicts rather than list of dicts

    import time
    
    # Build list of dicts
    list_of_dicts = list()
    for i in range(100000):
        list_of_dicts.append({'id': i, 'name': 'Tom'})
    
    # Build dict of dicts
    dict_of_dicts = dict()
    for i in range(100000):
        dict_of_dicts[i] = {'name': 'Tom'}
    
    
    # Find the one with ID of 99
    
    # 1. iterate through the list
    lod_ts = time.time()
    for elem in list_of_dicts:
        if elem['id'] == 99999:
            break
    lod_tf = time.time()
    lod_td = lod_tf - lod_ts
    
    # 2. Use filter
    f_ts = time.time()
    x = filter(lambda k: k['id'] == 99999, list_of_dicts)
    f_tf = time.time()
    f_td = f_tf- f_ts
    
    # 3. find it in dict of dicts
    dod_ts = time.time()
    x = dict_of_dicts[99999]
    dod_tf = time.time()
    dod_td = dod_tf - dod_ts
    
    
    print 'List of Dictionries took: %s' % lod_td
    print 'Using filter took: %s' % f_td
    print 'Dict of Dicts took: %s' % dod_td
    

    And the output is this:

    List of Dictionries took: 0.0099310874939
    Using filter took: 0.0121960639954
    Dict of Dicts took: 4.05311584473e-06
    

    Conclusion: Clearly having a dictionary of dicts is the most efficient way to be able to search in those cases, where you know say you will be searching by id's only. interestingly using filter is the slowest solution.

提交回复
热议问题