Kirk ERW
Kirk ERW

Reputation: 167

Extracting strings from a list of dictionaries

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

Answers (2)

Nipun Batra
Nipun Batra

Reputation: 11367

Although the above answer is correct, i will try and explain why OP's original code won't work.

  1. Firstly name of the variable. A comment on the original question explains it well enough
  2. You say why print list[0]['mid'] only gives the first value. The reason is that you are only giving list[0], which is a dictionary containing two keys, status and mid and you are trying to get the value corresponding to the "mid" key which will be a single value

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

Pavel Anossov
Pavel Anossov

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

Related Questions