您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python在JSON中查找值

使用Python在JSON中查找值

您必须遍历字典列表并使用给定的字典进行搜索id_number。一旦找到它,您就可以打印其其余数据并中断(假设id_number是唯一的)。

data = [
 {
   "id_number": "SA4784",
   "name": "Mark",
   "birthdate": None
 },
 {
   "id_number": "V410Z8",
   "name": "Vincent",
   "birthdate": "15/02/1989"
 },
 {
   "id_number": "CZ1094",
   "name": "Paul",
   "birthdate": "27/09/1994"
 }
]

for i in data:
    if i['id_number'] == 'V410Z8':
        print(i['birthdate'])
        print(i['name'])
        break

如果您可以控制数据结构,则更有效的方法是使用id_number键作为键(同样,假设id_number是唯一的):

data =  { "SA4784" : {"name": "Mark", "birthdate": None},
          "V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"},
          "CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"}
        }

然后,您需要做的就是尝试直接访问它:

try:
    print(data["V410Z8"]["name"])
except KeyError:
    print("ID doesn't exist")
>> "Vincent"
python 2022/1/1 18:52:58 有443人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶