Returning Value From List Within a Dict in Python

Attempting to return a specific value of a key that's in a list within a dict. I've tried iterating over items, searching specific ID's and not quite getting the result I'm after.

{
  'activeAccount': True,
  'country': 'USA',
  'state': 'CA',
  'users': [
    {
      'id': 'A',
      'firstName': 'Tom',
      'lastName': 'Cruise',
      'creditScore': '713',
      'balance': '65897.22',
      'debts': '12414.12',
      'savings': '15231.23'
    },
    {
      'id': 'B',
      'firstName': 'Jon',
      'lastName': 'Snow',
      'creditScore': '648',
      'balance': '12366.23',
      'debts': '522',
      'savings': '121588'
    },
    {
      'id': 'C',
      'firstName': 'Rick',
      'lastName': 'Sanchez',
      'creditScore': '655',
      'balance': '556425.33',
      'debts': '0',
      'savings': '125122.23'
    },
    {
      'id': 'D',
      'firstName': 'Monty',
      'lastName': 'Python',
      'creditScore': '815',
      'balance': '4512699.13',
      'debts': '4.25',
      'savings': '5499865.12'
    }
  ]
}

How would I retrieve a specific value of for example, the credit score of 'user id: 2' to return the value?

655

I've tried the solution of cScore = (dict['users'][2]['creditScore']), but this isn't ideal in situations of the objects changing order, etc.



Read more here: https://stackoverflow.com/questions/64397607/returning-value-from-list-within-a-dict-in-python

Content Attribution

This content was originally published by Stevaz at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: