我有一本字典"A":
A = {
"Industry1": 1,
"Industry2": 1,
"Industry3": 1,
"Customer1": 1,
"Customer2": 1,
"LocalShop1": 1,
"LocalShop2": 1,
}
我想按鍵名分組并為每個“類別”創建新詞典,名稱應該自動生成。
預期輸出:
Industry = {
"Industry1": 1,
"Industry2": 1,
"Industry3": 1,
}
Customer = {
"Customer1": 1,
"Customer2": 1,
}
LocalShop = {
"LocalShop1": 1,
"LolcalShop2": 1,
}
你們能給我一個實作這個輸出的提示嗎?
uj5u.com熱心網友回復:
假設您的密鑰在 中(KEYNAME)(NUM),您可以執行以下操作:
import re
from collections import defaultdict
from pprint import pprint
A = {
"Industry1": 1,
"Industry2": 1,
"Industry3": 1,
"Customer1": 1,
"Customer2": 1,
"LocalShop1": 1,
"LocalShop2": 1,
}
key_pattern = re.compile(r"[a-zA-Z] ")
result = defaultdict(dict)
for k, v in A.items():
key = key_pattern.search(k).group()
result[key][k] = v
pprint(dict(result))
輸出:
{'Customer': {'Customer1': 1, 'Customer2': 1},
'Industry': {'Industry1': 1, 'Industry2': 1, 'Industry3': 1},
'LocalShop': {'LocalShop1': 1, 'LocalShop2': 1}}
我創建了一個字典的字典,而不是為每個字典設定單獨的變數。它更易于管理,并且不會污染全域命名空間。
基本上你遍歷鍵值對和r"[a-zA-Z] "模式,你抓住沒有數字的部分。這就是將要用于外部字典中的鍵的內容。
uj5u.com熱心網友回復:
為了這個答案的目的,我假設字典 A 中的每個鍵都包含單詞“Industry”、“Customer”或“Shop”。這允許我們通過檢查每個鍵是否包含某個子字串(即“Industry”)來檢測每個條目需要屬于哪個類別。如果此假設不適用于您的特定情況,則您必須找到一種不同的方式來在下面的解決方案中撰寫更適合您的情況的 if/elif 陳述句。
這是一種方法。您為每個類別制作一個新詞典,并檢查每個鍵中是否包含“Industry”、“Customer”或“Shop”。
industries = {}
customers = {}
shops = {}
for key, value in A.items():
if "Industry" in key:
industries[key] = value
elif "Customer" in key:
customers[key] = value
elif "Shop" in key:
shops[key] = value
另一個更簡潔的版本是你有一個嵌套字典來存盤你所有的類別,每個類別在主類別中都有自己的字典。如果您需要添加更多類別,這將在將來有所幫助。您只需將它們添加到一個地方(在字典定義中),代碼就會自動調整。
categories = {
"Industry": {},
"Customer": {},
"Shop": {},
}
for key, value in A.items():
for category_name, category_dict in categories.items():
if category_name in key:
category_dict[key] = value
如果您無法從條目的字串中檢測到類別,那么您可能必須將該類別資訊存盤在鍵中或每個條目的值中A,以便在嘗試過濾所有內容時可以檢測到類別。
uj5u.com熱心網友回復:
您可以使用itertools.groupby只提取沒有數字的單詞的鍵。我不建議為它們創建變數,如果有超過 3 個鍵,這是不可擴展的……只需將它們放入新字典或串列中即可。
A = {'Industry1': 1,
'Industry2': 1,
'Industry3': 1,
'Customer1': 1,
'Customer2': 1,
'LocalShop1': 1,
'LocalShop2': 1}
grouped = [dict(val) for k, val in itertools.groupby(A.items(), lambda x: re.match('(. )\d{1,}', x[0]).group(1))]
輸出grouped:
[
{'Industry1': 1, 'Industry2': 1, 'Industry3': 1},
{'Customer1': 1, 'Customer2': 1},
{'LocalShop1': 1, 'LocalShop2': 1}
]
如果您確定該串列中恰好有 3 個元素并且您確實希望將它們作為變數,則可以通過元組解包來實作:
Industry, Customer, LocalShop = [dict(val) for k, val in itertools.groupby(A.items(), lambda x: re.match('(. )\d{1,}', x[0]).group(1))]
我想我會將結果保存在新字典中,并將分組鍵作為新鍵,將串列作為值:
grouped_dict = {k: dict(val) for k, val in itertools.groupby(A.items(), lambda x: re.match('(. )\d{1,}', x[0]).group(1))}
輸出grouped_dict:
{'Industry': {'Industry1': 1, 'Industry2': 1, 'Industry3': 1},
'Customer': {'Customer1': 1, 'Customer2': 1},
'LocalShop': {'LocalShop1': 1, 'LocalShop2': 1}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534509.html
標籤:Python字典
