尝试返回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查找用户,可以使用
filter
函数:说明
lambda u: u["id"] == "D"
表示:如果给定元素的属性“id”为“D”,则返回True它可以重写为普通函数:
filter( <condition> , dict["users"])
表示:遍历列表dict["users"]
并返回满足条件的所有元素(在本例中为“lambda”,也可以是任何返回True或False的函数)user = list( ... )[0]
由于筛选函数返回一个对象,因此需要将该对象转换为列表并获取列表的第一个元素另一个选项
您可以使用条件(id==“D”)构建列表理解,并获取列表的第一个元素:
'users'
的字典值是一个列表。因此,您必须遍历列表并搜索特定id这是你可以做到的
我搜索了
'id' == 'D'
。输出为815
词典的定义如下:
您必须遍历dict列表,查找id为2的dict。然后,返回该指令的信用分数。使用以下起始代码:
潜在的问题是您选择的数据表示形式与您的数据访问需求不匹配。如果您总是通过
id
引用您的帐户,则将列表更改为dict,并由该值键入。如果您通过各种方式查找帐户,那么您需要调查一些适合您的用例的数据库格式相关问题 更多 >
编程相关推荐