如何从 Python 中的字典中提取值?
how can I extract values from this dictionary in Python?
我有这样的字典:
{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
如何从此字典中提取 first_name
、last_name
、id
和 phone
值?
您应该使用例如将字符串转换为字典json.loads
。然后从普通的嵌套字典中提取 like。
示例:
import json
message = mydict["message"]
message_dict = json.loads(message)
message_dict['id']
其中 mydict
是您给定的输入字典。
如果您的代码段显示文件的内容,您可以执行以下操作:
with open(filepath) as file:
mydict = json.load(file)
message_dict = mydict["message"]
message_dict['id']
import json
# I have assumed your dictionary like that
data = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
# The data in "message" need to be loaded on JSON format to access it.
data["message"] = json.loads(data["message"])
# Now, you can print or whatever you want with all the data
print(data["message"]["id"])
print(data["message"]["first_name"])
print(data["message"]["last_name"])
print(data["message"]["phone"]) # There is phone info both in data["message"]["phone"] and data["phone"]. They are identical. You can use whichever you want.
# Optional
# If you want, you can assign data["message"] to a variable.
finalData = data["message"]
# Then you can access the info that you need from finalData
print(finalData["first_name"])
您可以使用以下代码提取这些值:
import json
str1 = r'{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}'
print(json.loads(json.loads(str1)['message'])['first_name'])
print(json.loads(json.loads(str1)['message'])['last_name'])
print(json.loads(json.loads(str1)['message'])['id'])
print(json.loads(json.loads(str1)['message'])['phone'])
另外,假设您的文件有新行分隔的字典,使用下面的代码解决了这个问题:
import json
fo = open(r"C:\Users\Downloads\test.txt", "r")
for each_line in fo.readlines():
print(json.loads(json.loads(each_line)['message'])['first_name'])
print(json.loads(json.loads(each_line)['message'])['last_name'])
print(json.loads(json.loads(each_line)['message'])['id'])
print(json.loads(json.loads(each_line)['message'])['phone'])
这是另一种方法:
import json
D = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
data = json.loads(D['message'])
for key in ['first_name', 'last_name', 'phone', 'id']:
print(f'{key} -> {data.get(key, "?")}')
我有这样的字典:
{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
如何从此字典中提取 first_name
、last_name
、id
和 phone
值?
您应该使用例如将字符串转换为字典json.loads
。然后从普通的嵌套字典中提取 like。
示例:
import json
message = mydict["message"]
message_dict = json.loads(message)
message_dict['id']
其中 mydict
是您给定的输入字典。
如果您的代码段显示文件的内容,您可以执行以下操作:
with open(filepath) as file:
mydict = json.load(file)
message_dict = mydict["message"]
message_dict['id']
import json
# I have assumed your dictionary like that
data = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
# The data in "message" need to be loaded on JSON format to access it.
data["message"] = json.loads(data["message"])
# Now, you can print or whatever you want with all the data
print(data["message"]["id"])
print(data["message"]["first_name"])
print(data["message"]["last_name"])
print(data["message"]["phone"]) # There is phone info both in data["message"]["phone"] and data["phone"]. They are identical. You can use whichever you want.
# Optional
# If you want, you can assign data["message"] to a variable.
finalData = data["message"]
# Then you can access the info that you need from finalData
print(finalData["first_name"])
您可以使用以下代码提取这些值:
import json
str1 = r'{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}'
print(json.loads(json.loads(str1)['message'])['first_name'])
print(json.loads(json.loads(str1)['message'])['last_name'])
print(json.loads(json.loads(str1)['message'])['id'])
print(json.loads(json.loads(str1)['message'])['phone'])
另外,假设您的文件有新行分隔的字典,使用下面的代码解决了这个问题:
import json
fo = open(r"C:\Users\Downloads\test.txt", "r")
for each_line in fo.readlines():
print(json.loads(json.loads(each_line)['message'])['first_name'])
print(json.loads(json.loads(each_line)['message'])['last_name'])
print(json.loads(json.loads(each_line)['message'])['id'])
print(json.loads(json.loads(each_line)['message'])['phone'])
这是另一种方法:
import json
D = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}
data = json.loads(D['message'])
for key in ['first_name', 'last_name', 'phone', 'id']:
print(f'{key} -> {data.get(key, "?")}')