3

I have some output data in this format:

[{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

This data can contain any number of entries. What I want to do is pull out all the sname values into a list like this:

snames = ['sig1','sig2','sig3','sig4']

How can I iterate over the output without knowing its length in advance?

0

3 Answers 3

3

You can use a list comprehension to do this:

In [1]: array_of_dicts = [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

In [2]: snames = [d['sname'] for d in array_of_dicts]

In [3]: print snames
['sig1', 'sig2', 'sig3', 'sig4']
Sign up to request clarification or add additional context in comments.

Comments

2

You can use list comprehension.

With

my_dict_list = [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

You can get all 'sname' entries via:

my_list = [x['sname'] for x in my_dict_list]

and

print(my_list)

prints

['sig1', 'sig2', 'sig3', 'sig4']

Comments

2

The shortest and most pythonic is to use a list comprehension :

data =  [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]

snames = [i['sname'] for i in data if 'sname' in i]

print(snames)
>>> ['sig1', 'sig2', 'sig3', 'sig4']

It's better to verify that 'sname' is in your dict or you might get a KeyError unless you are sure about their consistency (you could get rid of if 'sname' in i in that case).

2 Comments

I would only start checking if I know that there are some dictionaries in the list that don't contain the Key. Otherwise potential unwanted errors in the nested data structure may not be detected. But I guess that heavily depends on the problem.
You're right, I had it "just in case" guessing that if we are not sure about the length, it could also be uncertain regarding the dicts. I added a precision in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.