Python Accessing Values in A List of Dictionaries

后端 未结 6 1346
时光说笑
时光说笑 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 05:16

    If you want a list of those values:

    >>> [d['Name'] for d in thisismylist]
    ['Albert', 'Suzy', 'Johnny']
    

    Same method, you can get a tuple of the data:

    >>> [(d['Name'],d['Age']) for d in thisismylist]
    [('Albert', 16), ('Suzy', 17), ('Johnny', 13)]
    

    Or, turn the list of dicts into a single key,value pair dictionary:

    >>> {d['Name']:d['Age'] for d in thisismylist}
    {'Johnny': 13, 'Albert': 16, 'Suzy': 17}
    

    So, same method, a way to print them:

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

    And you can print it sorted if you wish:

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

    Or, sort by their ages while flattening the list:

    >>> for name, age in sorted([(d['Name'],d['Age']) for d in thisismylist],key=lambda t:t[1]):
    ...    print '{}: {}'.format(name,age)
    ... 
    Johnny: 13
    Albert: 16
    Suzy: 17
    

提交回复
热议问题