我正在嘗試使用簡單的 Python 代碼將字典串列合并到一個精簡串列中,因為我有很多重復的 atm。
由此:
[
{
"module": "RECEIPT BISCUITS",
"product_range": "ULKER BISCUITS",
"receipt_category": "BISCUITS"
},
{
"module": "RECEIPT BISCUITS",
"product_range": "ULKER",
"receipt_category": "BISCUITS"
},
{
"module": "RECEIPT BISCUITS",
"product_range": "ULKER BISCUITS GOLD",
"receipt_category": "BISCUITS GOLD"
},
{
"module": "RECEIPT COFFEE",
"product_range": "BLACK GOLD",
"receipt_category": "BLACK GOLD"
}
]
對此:
[
{
"module": "RECEIPT BISCUITS",
"product_range": ["ULKER BISCUITS", "ULKER"],
"receipt_category": ["BISCUITS", "BISCUITS GOLD"]
},
{
"module": "RECEIPT COFFEE",
"product_range": ["BLACK GOLD"],
"receipt_category": ["BLACK GOLD"]
}
]
該模塊用于在它們之間進行排序,而其他 2 個將存盤為串列,即使只有一個值。這是 JSON 格式順便說一句。
uj5u.com熱心網友回復:
collections.defaultdict 來拯救您的資料重組需求!
import collections
data = [
{"module": "RECEIPT BISCUITS", "product_range": "ULKER BISCUITS", "receipt_category": "BISCUITS"},
{"module": "RECEIPT BISCUITS", "product_range": "ULKER", "receipt_category": "BISCUITS"},
{"module": "RECEIPT BISCUITS", "product_range": "ULKER BISCUITS GOLD", "receipt_category": "BISCUITS GOLD"},
{"module": "RECEIPT COFFEE", "product_range": "BLACK GOLD", "receipt_category": "BLACK GOLD"},
]
grouped = collections.defaultdict(lambda: collections.defaultdict(list))
group_key = "module"
for datum in data:
datum = datum.copy() # Copy so we can .pop without consequence
group = datum.pop(group_key) # Get the key (`module` value)
for key, value in datum.items(): # Loop over the rest and put them in the group
grouped[group][key].append(value)
collated = [
{
group_key: group,
**values,
}
for (group, values) in grouped.items()
]
print(collated)
列印出來
[
{'module': 'RECEIPT BISCUITS', 'product_range': ['ULKER BISCUITS', 'ULKER', 'ULKER BISCUITS GOLD'], 'receipt_category': ['BISCUITS', 'BISCUITS', 'BISCUITS GOLD']},
{'module': 'RECEIPT COFFEE', 'product_range': ['BLACK GOLD'], 'receipt_category': ['BLACK GOLD']}
]
請注意,這不會對 中的值進行重復資料洗掉product_range,因為我不確定值的順序對您是否重要,以及是否使用集合(不保留順序)。
更改list到set并append以add將使值是唯一的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315997.html
