0

The following is my code snippet. I am trying to extract the value of 'string' and 'score' from a nested dictionary within a nested list . How do I accomplish this?

Expected output would be 'Object element' and '1.0'

[{'Form': [{'string': 'object element', 'score': 1.0,}],
  'types': ['http://google.com'],
'threshold':34}]

2
  • 1
    What have you tried? Do you want this done in a loop, or simply extract the value of the first(only) 'string' and 'score' values? Also, I think the final braces might be a bit mixed up? Commented Apr 28, 2019 at 19:32
  • I tried to flatten the list first through reduce function and then tried to unpack the value via list indexing, but no luck.. Yes, I want this to be done in a loop. Commented Apr 28, 2019 at 19:38

1 Answer 1

3

This should work

data = [{'Form': [{'string': 'object element', 'score': 1.0,}], 'types': ['http://google.com'], 'threshold':34},{'Form': [{'string': 'data store', 'score': 0.9,}], 'types': ['http://google.com'], 'threshold':23}]

for d in data:
    print(d['Form'][0]['string'])
    print(d['Form'][0]['score'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Nithin. Actually I missed stating my problem clearly. I would ideally like the solution in loop cos my code is of below format [{'Form': [{'string': 'object element', 'score': 1.0,}], 'types': ['http://google.com'], 'threshold':34},{'Form': [{'string': 'data store', 'score': 0.9,}], 'types': ['http://google.com'], 'threshold':23}]
Thanks a ton @Nithin. This is exactly what I was looking for.

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.