Getting a list of values from a list of dicts

前端 未结 9 703
执念已碎
执念已碎 2020-11-22 15:22

I have a list of dicts like this:

[{\'value\': \'apple\', \'blah\': 2}, 
 {\'value\': \'banana\', \'blah\': 3} , 
 {\'value\': \'cars\', \'blah\': 4}]
         


        
9条回答
  •  情深已故
    2020-11-22 15:36

    I think as simple as below would give you what you are looking for.

    In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
    In[6]: ld = [d.get('value', None) for d in ll]
    In[7]: ld
    Out[7]: ['apple', 'banana', 'cars']
    

    You can do this with a combination of map and lambda as well but list comprehension looks more elegant and pythonic.

    For a smaller input list comprehension is way to go but if the input is really big then i guess generators are the ideal way.

    In[11]: gd = (d.get('value', None) for d in ll)
    In[12]: gd
    Out[12]:  at 0x7f5774568b10>
    In[13]: '-'.join(gd)
    Out[13]: 'apple-banana-cars'
    

    Here is a comparison of all possible solutions for bigger input

     In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
    In[3]: def gen_version():
      ...:     for i in l:
      ...:         yield i.get('value', None)
      ...: 
    In[4]: def list_comp_verison():
      ...:     return [i.get('value', None) for i in l]
      ...: 
    In[5]: def list_verison():
      ...:     ll = []
      ...:     for i in l:
      ...:         ll.append(i.get('value', None))
      ...:     return ll
    In[10]: def map_lambda_version():
       ...:      m = map(lambda i:i.get('value', None), l)
       ...:      return m
       ...: 
    In[11]: %timeit gen_version()
    172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    In[12]: %timeit map_lambda_version()
    203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    In[13]: %timeit list_comp_verison()
    1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    In[14]: %timeit list_verison()
    2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    As you can see, generators are a better solution in comparison to the others, map is also slower compared to generator for reason I will leave up to OP to figure out.

提交回复
热议问题