Iterating over list of dictionaries

后端 未结 4 1119
星月不相逢
星月不相逢 2020-12-02 14:36

I have a list -myList - where each element is a dictionary. I wish to iterate over this list but I am only interesting in one attribute - \'age\' - in each dictionary each

相关标签:
4条回答
  • 2020-12-02 15:05

    For printing, probably what you're doing is just about right. But if you want to store the values, you could use a list comprehension:

    >>> d_list = [dict((('age', x), ('foo', 1))) for x in range(10)]
    >>> d_list
    [{'age': 0, 'foo': 1}, {'age': 1, 'foo': 1}, {'age': 2, 'foo': 1}, {'age': 3, 'foo': 1}, {'age': 4, 'foo': 1}, {'age': 5, 'foo': 1}, {'age': 6, 'foo': 1}, {'age': 7, 'foo': 1}, {'age': 8, 'foo': 1}, {'age': 9, 'foo': 1}]
    >>> ages = [d['age'] for d in d_list]
    >>> ages
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> len(ages)
    10
    
    0 讨论(0)
  • 2020-12-02 15:13

    Very simple way, list of dictionary iterate

    >>> my_list
    [{'age': 0, 'name': 'A'}, {'age': 1, 'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]
    
    >>> ages = [li['age'] for li in my_list]
    
    >>> ages
    [0, 1, 2, 3, 4, 5]
    
    0 讨论(0)
  • 2020-12-02 15:13

    The semicolons at the end of lines aren't necessary in Python (though you can use them if you want to put multiple statements on the same line). So it would be more pythonic to omit them.

    But the actual iteration strategy is easy to follow and pretty explicit about what you're doing. There are other ways to do it. But an explicit for-loop is perfectly pythonic.

    (Niklas B.'s answer will not do precisely what you're doing: if you want to do something like that, the format string should be "{0}\n{1}".)

    0 讨论(0)
  • 2020-12-02 15:18

    You could use a generator to only grab ages.

    # Get a dictionary 
    myList = [{'age':x} for x in range(1,10)]
    
    # Enumerate ages
    for i, age in enumerate(d['age'] for d in myList): 
        print i,age
    

    And, yeah, don't use semicolons.

    0 讨论(0)
提交回复
热议问题