我想從字典中的串列中洗掉重復值。我正在嘗試使可配置代碼適用于任何領域,而不是使特定領域。
輸入資料 :
{'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['[email protected]', '[email protected]']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280, 12177218280]}]}
預期輸出資料:
{'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['[email protected]']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280]}]}
代碼嘗試:
dic = {'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['[email protected]', '[email protected]']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280, 12177218280]}]}
res = []
for i in dic:
if i not in res:
res.append(i)
uj5u.com熱心網友回復:
您可以使用 set()
import json
dic = {
'Customer_Number': 90617174,
'Email': [
{
'Email_Type': 'Primary',
'Email': list(set([
'[email protected]',
'[email protected]',
]))
}
],
'Phone_Number': [
{
'Phone_Type': 'Mobile',
'Phone': list(set([
12177218280,
12177218280,
]))
}
]
}
print(json.dumps(dic,indent=2))
如果您想在dic's串列上執行此操作,則可以這樣做:
for dic in dics:
for email in dic['Email']:
email['Email'] = list(set(email['Email']))
for phone in dic['Phone_Number']:
phone['Phone'] = list(set(phone['Phone']))
uj5u.com熱心網友回復:
您開始使用的方法,您需要更深入幾個級別以找到每個這樣的“重復”串列并對其進行重復資料洗掉。
要進行重復資料洗掉,您可以使用set- 這也是一個“容器”資料結構,就像 alist但有一些(很多?)差異。您可以在官方 python 檔案中對所有這些進行很好的介紹-
for key in dic:
if isinstance(dic[key], list):
for inner_dict in dic[key]:
for inner_key in inner_dict:
if isinstance(inner_dict[inner_key], list):
inner_dict[inner_key] = list(set(inner_dict[inner_key]))
print(dic)
#{'Customer_Number': 90617174,
# 'Email': [{'Email_Type': 'Primary', 'Email': ['[email protected]']}],
# 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280]}]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363332.html
上一篇:jq~折疊特定的單個物件陣列?
