Reputation: 167
How can I print only the "mid" or the "status" in this list of dictionaries?
list = [{'status': 'OK', 'mid': '6269'}, {'status': 'OK', 'mid': '6270'},{'status': 'OK', 'mid': '6271'}, {'status': 'OK', 'mid': '6272'}, {'status': 'OK', 'mid': '6273'}, {'status': 'OK', 'mid': '6274'},{'status': 'OK', 'mid': '6288'}, {'status': 'OK', 'mid': '6289'}]
I tried : print list[0]['mid']
but it is only giving the 'mid' value for the first item in the list? How can i do it for the whole list
?
Upvotes: 1
Views: 98
Reputation: 11367
Although the above answer is correct, i will try and explain why OP's original code won't work.
If you haven't worked with List Comprehensions before you could do with a simple for loop, which ranges from 0 to length of your list. Or use for item in list type of iteration.
Upvotes: 1
Reputation: 62908
Use a list comprehension:
data = [{'status': 'OK', 'mid': '6269'},
{'status': 'OK', 'mid': '6270'},
{'status': 'OK', 'mid': '6271'},
{'status': 'OK', 'mid': '6272'},
{'status': 'OK', 'mid': '6273'},
{'status': 'OK', 'mid': '6274'},
{'status': 'OK', 'mid': '6288'},
{'status': 'OK', 'mid': '6289'}]
print [item['mid'] for item in data]
PS: don't name your variables list
, you cannot use the built-in list
then.
Upvotes: 8