【问题标题】:Returning value from list within a dict从字典中的列表返回值
【发布时间】:2021-01-31 11:23:24
【问题描述】:

试图返回 dict 列表中键的特定值。我尝试迭代项目,搜索特定 ID,但并没有完全得到我想要的结果。

{
  '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'
    }
  ]
}

如何检索特定值,例如users[2] 的信用评分以返回该值?

655

我已经尝试过cScore = (dict['users'][2]['creditScore'])的解决方案,但这在对象更改顺序等情况下并不理想。

【问题讨论】:

  • 为什么要分配一个唯一的 ID,然后不将该 ID 用作键?最有意义的数据结构 (IMO) 将是一个字典,其中键是唯一的用户 ID,值应该是与用户相关的信息的键/值对字典。这样,您就不必担心列表索引,您可以使用users[C][creditScore] 检索您想要的信息。
  • 您的问题不清楚。您要查找列表中第三个用户users[2] 的信用评分,id j=key 等于2 的用户?

标签: python


【解决方案1】:

您必须遍历字典列表,查找 id 为 2 的字典。然后从该字典返回信用评分。使用此入门代码:

for account in data_base:
    if account['id'] == 2:
        score = account['creditScore']
        break

您的根本问题是您选择的数据表示不符合您的数据访问需求。如果您总是通过id 引用您的帐户,那么将您的列表更改为一个字典,由该值键入。如果您通过各种方式查找帐户,那么您需要研究一些适合您的用例的数据库格式。

【讨论】:

    【解决方案2】:

    'users' 的字典值是一个列表。所以你必须遍历列表并搜索特定的 id。

    你可以这样做。

    for i in cust['users']:
        if i['id'] == '2':
            print (i['creditScore'])
    

    我搜索了'id' == 'D'。输出为815

    字典定义为:

    cust = {
      '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'
        }
      ]
    }
    

    【讨论】:

      【解决方案3】:

      如果您需要在用户列表中通过 ID 查找用户,您可以使用 filter 函数:

      dict = {
        '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'
          }
        ]
      }
      
      # get the user with ID:"D"
      user = list(filter(lambda u: u["id"] == "D", dict["users"]))[0]
      
      # get the value
      cScore = user["creditScore"]    # <-- Output: 815
      
      

      说明

      lambda u: u["id"] == "D" 表示:如果给定元素的属性“id”是“D”,则返回 True。

      可以重写为普通函数:

      def check_D(user):
          return user["id"] == "D"
      
      user = list(filter(check_D, dict["users"]))[0]
      

      filter( &lt;condition&gt; , dict["users"]) 表示:遍历列表dict["users"] 并返回所有满足条件的元素(在本例中为“lambda”,或者它可以是任何返回 True 或 False 的函数)。

      user = list( ... )[0]由于过滤器函数返回一个对象,所以需要将对象转换为列表,并获取列表的第一个元素。

      另一种选择

      您可以使用条件 (id == "D") 构建列表推导式并获取列表的第一个元素:

      creditScore = [usr["creditScore"] for usr in dict["users"] if usr["id"] == "D"][0]
      
      print(creditScore) # <-- Output: 815
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-09
        • 2013-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多