0

I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

[{
    "FullMeasure": "1/2 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1142, 
    "IngredientName": "frozen corn", 
    "IngredientStep": 10, 
    "LanguageId": 0, 
    "PostPreparation": ", thawed, drained", 
    "PrePreparation": "", 
    "QuantityNum": 0, 
    "QuantityText": "1/2", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291555, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "1/4 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1523, 
    "IngredientName": "red pepper", 
    "IngredientStep": 20, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "chopped", 
    "QuantityNum": 0, 
    "QuantityText": "1/4", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291554, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "2 Tbsp.", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 20197, 
    "IngredientName": "chopped green chiles", 
    "IngredientStep": 30, 
    "LanguageId": 0, 
    "PostPreparation": ", drained", 
    "PrePreparation": "canned ", 
    "QuantityNum": 2, 
    "QuantityText": "2", 
    "QuantityUnit": "Tbsp.", 
    "RecipeIngredientID": 6291552, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  },
{
    "FullMeasure": "", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 19682, 
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice", 
    "IngredientStep": 80, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "", 
    "QuantityNum": 4, 
    "QuantityText": "4", 
    "QuantityUnit": "", 
    "RecipeIngredientID": 6291558, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }
]

I will like to get all the ingredientID, so i wrote this little piece of code to grab the IngredientID

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }

when i return the value, i get

{
  "Ingreient ID": 19682
}

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

2
  • It will be helpful if you tell in what format the data, you are expecting. Commented Apr 3, 2017 at 4:47
  • Are you sure this is a python list parsed? because the variable "null" is not defined? I supposed you will have to parse it json first or else you will get an error Commented Apr 3, 2017 at 4:58

9 Answers 9

1

You are replacing the value every time through that loop. You should be adding to the value, instead.

So first create the value as an empty list (before the loop), then on each iteration of the loop, append to that list:

value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
    value.append({'Ingredient ID': records['IngredientID']})

However, having a list of dictionaries, where each dictionary has one single value with the same known key, seems a bit pointless. Depending on your requirements, you probably may want to do either this:

    value.append(rec)

or

    value.append(records['IngredientID'])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i can't believe i didn't think about this, I guess i over thought everything or just didn't think it through. Thank you.
0

What you're doing right now is that you're redefining value again every loop. You will need to define value before the loop and assign it to an empty list that you can add to.

value = {'Ingredient ID':[]}
for records in rec:
    value['Ingredient ID'].append(records['IngredientID'])

You can also define value as a list like this:

value = []
for records in rec:
    value.append(records['IngredientID'])

Comments

0

You are re-assigning variable value everytime. Hence you are getting the last element. Instead you should try

# Your code
value = []
for records in rec:
    value.append(records['IngredientID']);

# print value     # this will have all required IngredientID

Comments

0

One issue with your current implementation is that the value of value will be over-written each time you find a new ingredient ID. If you need to get a list of values, then you have to make sure that you keep all of the old values even when adding a new one.

If you make values a list and then use append, you'll get all of the values you are looking for:

values = []
for records in rec:
    ingredient_id = records.get('IngredientID', None)
    if ingredient_id:
        values.append(ingredient_id)

It is a good idea to use the dict.get() method to retrieve a value and then check if it exists; otherwise you may end up with an exception.

Comments

0

If you just wanted the ids, you could use a list comprehension, something like this:

ids = [records['IngredientID'] for records in recipes['Recipes'][0]['Ingredients']]

Comments

0

You're overwriting the value inside the loop. So, the final result would be the last ingredient_id in the json. Try instead try adding the value to a list:

myList = []

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
            myList.append(value)

myList will have all the ingredients

You can even have a one liner to do this:

[r['IngredientID'] for r in rec]

This will give a list as ['1142',1523,..]

Comments

0

Yet another approach, the defaultdict

from collections import defaultdict
recipe_ids = defaultdict(list)
for records in rec:
    recipe_ids['recipe id'].append(records.get('IngredientID'))

Comments

0

If you want just the list of the IngredientID, then use [rec['IngredientID'] for rec in records]

records = [{
    "FullMeasure": "1/2 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1142, 
    "IngredientName": "frozen corn", 
    "IngredientStep": 10, 
    "LanguageId": 0, 
    "PostPreparation": ", thawed, drained", 
    "PrePreparation": "", 
    "QuantityNum": 0, 
    "QuantityText": "1/2", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291555, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "1/4 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1523, 
    "IngredientName": "red pepper", 
    "IngredientStep": 20, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "chopped", 
    "QuantityNum": 0, 
    "QuantityText": "1/4", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291554, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "2 Tbsp.", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 20197, 
    "IngredientName": "chopped green chiles", 
    "IngredientStep": 30, 
    "LanguageId": 0, 
    "PostPreparation": ", drained", 
    "PrePreparation": "canned ", 
    "QuantityNum": 2, 
    "QuantityText": "2", 
    "QuantityUnit": "Tbsp.", 
    "RecipeIngredientID": 6291552, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  },
{
    "FullMeasure": "", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 19682, 
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice", 
    "IngredientStep": 80, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "", 
    "QuantityNum": 4, 
    "QuantityText": "4", 
    "QuantityUnit": "", 
    "RecipeIngredientID": 6291558, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }
]

[rec['IngredientID'] for rec in records]

Output:

[1142, 1523, 20197, 19682]

Comments

0

Given the number of answers I figured hey why not one more.
If you have complicated expressions, you may want to look at jmespath, which is like xslt for json, e.g.:

>>> import jmespath
>>> jmespath.search('Recipes[0].Ingredients[*].IngredientID', recipes)
[1142, 1523, 20197, 19682]

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.