从dict中的列表返回值

2024-10-02 18:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试返回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'])的解决方案,但在对象改变顺序等情况下,这并不理想


Tags: idtrue列表firstnamecountryusersdictbalance
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( <condition> , 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

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

您必须遍历dict列表,查找id为2的dict。然后,返回该指令的信用分数。使用以下起始代码:

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

潜在的问题是您选择的数据表示形式与您的数据访问需求不匹配。如果您总是通过id引用您的帐户,则将列表更改为dict,并由该值键入。如果您通过各种方式查找帐户,那么您需要调查一些适合您的用例的数据库格式

相关问题 更多 >