這是要點,我使用 Django 來填充 PostgreSQL 資料庫,以存盤來自第三方 API 的用戶資料。我正在使用 API 將資料匯入 Django,以便我可以自動填充資料庫。我為需要存盤的欄位構建了模型。
這是我需要幫助的地方。我已經從 API 回應創建了一個串列,但我想洗掉重復的用戶并合并這些串列,就像這樣。
What I have now.
{
"person_id": "1",
"account": "5",
"list": "c"
},
{
"person_id": "1",
"account": "5",
"list": "b"
},
{
"person_id": "1",
"account": "5",
"list": "a"
},
...
What i want
{
"person_id": "1",
"account": "5",
"list": ["a","b","c"]
},
{
"person_id": "2",
"account": "5",
"list": ["a","c"]
},
{
"person_id": "3",
"account": "5"
"list": ["a","b"]
},
...
我正在進行的一個 API 呼叫是將所有用戶都放在一個串列中并回復:
API RESPONSE
{
"records": [
{
"id": "asdafdgsdfhsdfh",
"email": "[email protected]",
"phone_number": " 1123123"
},
{
"id": "asdafdgsdfhsdfh",
"email": "[email protected]",
"phone_number": " 1123123"
},
...
],
"marker":342523452
}
根據該回應,我正在迭代每條記錄并創建一個 dict 以添加到串列中。
def personA():
return dict(
person_id = record["id"],
account = account,
list = list
r = requests.request('GET',f"{link}")
resdata =r.json()
for r in resdata:
for record in resdata["records"]:
listC = personA()
listData.append(listC)
)
我正在為帳戶中的每個串列執行此操作,因此某些“person_id”出現多次,而某些僅出現一次。
以我想要的方式創建串列的最佳方式是什么?
uj5u.com熱心網友回復:
您可以創建人員到他們出現的串列的映射:
from collections import defaultdict
separate_data = [
{
"person_id": "1",
"account": "5",
"list": "c"
},
{
"person_id": "1",
"account": "5",
"list": "b"
},
{
"person_id": "1",
"account": "5",
"list": "a"
},
]
merged = defaultdict(list)
for record in separate_data:
key = record["person_id"], record["account"]
value = record["list"]
merged[key].append(value)
results = [
{
"person_id": person_id,
"account": account,
"list": sorted(lists)
} for (person_id, account), lists in merged.items()
]
給
[{'account': '5', 'list': ['a', 'b', 'c'], 'person_id': '1'}]
uj5u.com熱心網友回復:
字典將在這里完成:
# Grab the account_id from the first element in data. I'm assuming that the account names are the same across all data points, but this is not a serious concern per the comment.
account_id = data[0]["account"]
# We maintain a dictionary that maps from a person_id to a list of strings appearing in the list field for a given person_id.
person_id_elements = {}
# Read each data point into our dictionary.
for data_point in data:
person_id = data_point["person_id"]
list_element = data_point["list"]
if person_id not in person_id_elements:
person_id_elements[person_id] = []
person_id_elements[person_id].append(list_element)
# Transform id_data into objects that observe the desired schema.
result = []
for person_id in person_id_elements:
result.append({
"person_id": person_id,
"account": account_id,
"list": sorted(person_id_elements[person_id]) # Sorted, as shown in the sample output.
})
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395684.html
上一篇:如何從Prometheus服務器獲取按特定標簽過濾的所有指標名稱
下一篇:字母出現串列Python
