Python Accessing Values in A List of Dictionaries

后端 未结 6 1382
时光说笑
时光说笑 2020-12-24 04:51

Say I have a List of dictionaries that have Names and ages and other info, like so:

thisismylist= [  
              {\'Name\': \'Albert\' , \'Age\': 16},
          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 04:55

    You could project the Name attribute out of each element in the list and join the results with newlines:

    >>> print '\n'.join(x['Name'] for x in thisismylist)
    Albert
    Suzy
    Johnny
    

    Edit

    It took me a few minutes, but I remembered the other interesting way to do this. You can use a combination of itertools and the operator module to do this as well. You can see it on repl.it too.

    >>> from itertools import imap
    >>> from operator import itemgetter
    >>> print '\n'.join(imap(itemgetter('Name'), thisismylist))
    Albert
    Suzy
    Johnny
    

    In any case, you are probably better off using a vanilla for loop, but I figured that some other options were in order.

提交回复
热议问题