0

I have written a function which will return several dictionaries. For example:

def func()
    return c # <---- nested dictionary

if __name__ == "__main__":
    ans = func()
    print ans             

If I print the ans:

{u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)},
print ans.get('_id')

If I print this, the result is None. How can I get _id?

9
  • ans.get('result')[0].get('_id') ? Commented Mar 15, 2015 at 8:17
  • I can get the result , but only the first one.. how can get all results? Commented Mar 15, 2015 at 8:20
  • [i['_id'] for i in ans['result']] Commented Mar 15, 2015 at 8:20
  • the 0 is the first index. for the remaining, you could use a for loop Commented Mar 15, 2015 at 8:21
  • I can get all results!! thank all of you!!!! Commented Mar 15, 2015 at 8:23

4 Answers 4

2

You could use a list comprehension.

In [19]: ans = {u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)}]}
In [24]: [i['_id'] for i in ans['result']]
Out[24]: [datetime.datetime(2015, 2, 23, 9, 32), datetime.datetime(2015, 2, 23, 9, 33)]
In [25]: [i.get('_id') for i in ans['result']]
Out[25]: [datetime.datetime(2015, 2, 23, 9, 32), datetime.datetime(2015, 2, 23, 9, 33)]
Sign up to request clarification or add additional context in comments.

Comments

0
for i in ans['result']:
    print i['_id']

1 Comment

This will only return the first result item's _id - the OP is interested in getting all of the _id values.
0

From looking at your trace it seems that c is a dictionary containing various other dictionary.

print ans["result"][0]["_id"]

Should return the value you want.

Comments

0

func() is actually returning a nested dictionary. Look closely at what your print is telling you. So ans = func() is a nested dictionary:

{u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)},

Hence ans['result'] is itself another dict, or apparently a list containing a dict.

Comments

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.