Filter dict to contain only certain keys?

后端 未结 15 1162
耶瑟儿~
耶瑟儿~ 2020-11-22 10:52

I\'ve got a dict that has a whole bunch of entries. I\'m only interested in a select few of them. Is there an easy way to prune all the other ones out?

15条回答
  •  暖寄归人
    2020-11-22 11:37

    Code 1:

    dict = { key: key * 10 for key in range(0, 100) }
    d1 = {}
    for key, value in dict.items():
        if key % 2 == 0:
            d1[key] = value
    

    Code 2:

    dict = { key: key * 10 for key in range(0, 100) }
    d2 = {key: value for key, value in dict.items() if key % 2 == 0}
    

    Code 3:

    dict = { key: key * 10 for key in range(0, 100) }
    d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}
    

    All pieced of code performance are measured with timeit using number=1000, and collected 1000 times for each piece of code.

    For python 3.6 the performance of three ways of filter dict keys almost the same. For python 2.7 code 3 is slightly faster.

提交回复
热议问题