代码之家  ›  专栏  ›  技术社区  ›  murkywaters

如何解析出现在字典键值之前的文本?

  •  0
  • murkywaters  · 技术社区  · 6 年前

    我不确定如何最好地描述它,但是如果我有一个字典,它在实际键值之前有文本或名称,我如何从字典中提取它以得到实际的键值对?

    {'students':[
    {'username': 'Mike1@example.com', 'enabledUser': true, 'password': null, 'identifier': '996_STU_10100001', 'dateLastModified': '2018-08-01T17:13:40.003Z', 'middleName': 'Sierra', 'userIds': null, 'familyName': 'Aadgoo', 'sms': null, 'phone': '8888880001', 'grades': ['01'], 'sourcedId': 'STU_10100001', 'role': 'student', 'status': 'active', 'orgs': [{'href': '~/ims/oneroster/v1p1/orgs/996', 'type': 'org', 'sourcedId': '996'}], 'agents': [], 'givenName': 'Mike', 'email': 'Mike1@example.com', 'metadata': null}
    {'username': 'Jonathan2@example.com', 'enabledUser': true, 'password': null, 'identifier': '996_STU_10100002', 'dateLastModified': '2018-08-01T17:13:40.003Z', 'middleName': 'Alpha', 'userIds': null, 'familyName': 'Bravo', 'sms': null, 'phone': '8888880002', 'grades': ['05'], 'sourcedId': 'STU_10100002', 'role': 'student', 'status': 'active', 'orgs': [{'href': '~/ims/oneroster/v1p1/orgs/996', 'type': 'org', 'sourcedId': '996'}], 'agents': [], 'givenName': 'Jonathan', 'email': 'Johnathan2@example.com', 'metadata': null}...]}
    

    要从中提取的所需键值:

    'username': 'Mike1@example.com', 'enabledUser': true, 'password': null, 'identifier': '996_STU_10100001', 'dateLastModified': '2018-08-01T17:13:40.003Z', 'middleName': 'Sierra', 'userIds': null, 'familyName': 'Aadgoo', 'sms': null, 'phone': '8888880001', 'grades': ['01'], 'sourcedId': 'STU_10100001', 'role': 'student', 'status': 'active', 'orgs': [{'href': '~/ims/oneroster/v1p1/orgs/996', 'type': 'org', 'sourcedId': '996'}], 'agents': [], 'givenName': 'Mike', 'email': 'Mike1@example.com', 'metadata': null
    'username': 'Jonathan2@example.com', 'enabledUser': true, 'password': null, 'identifier': '996_STU_10100002', 'dateLastModified': '2018-08-01T17:13:40.003Z', 'middleName': 'Alpha', 'userIds': null, 'familyName': 'Bravo', 'sms': null, 'phone': '8888880002', 'grades': ['05'], 'sourcedId': 'STU_10100002', 'role': 'student', 'status': 'active', 'orgs': [{'href': '~/ims/oneroster/v1p1/orgs/996', 'type': 'org', 'sourcedId': '996'}], 'agents': [], 'givenName': 'Jonathan', 'email': 'Johnathan2@example.com', 'metadata': null
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   nauer    6 年前

    我想你是说嵌套式听写。所以外部dict的值是dict。在您的例子中,它是dict列表的dict。

    您的“听写”[学生][0][用户名]

    要获得可以使用的键值

    您的“听写键”()

    或在一个循环中

    for key in your_dict:
       for list_item in your_dict[key]:
          for key2 in list_item:
             print(key2, list_item[key2])
    
        2
  •  1
  •   Alan Raso    6 年前

    您可以将其放到变量上并运行:

    for dic in variable['students']:
      do_something_with_dic(dic) # dic -> your key-value pairs
    

    如果这是你代码上的字典,你可能需要修正一些东西,比如 true -gt; True .