[英]convert list of lists into nested dictionary
我有如下列表
l = [( "tx", 'houston', 'richmond'),
("tx", 'dallas', 'lakewood'),
( "tx", 'houston', 'kessler'),
( "tx", 'dallas', 'cedars'),
( "ct", 'hartford', 'wethersfield'),
( "ct", 'hartford', 'parkville'),
( "ct", 'new haven', 'westville'),
( "fl", 'miami', 'gladview'),
("fl", 'orlando', 'parramore'),
( "fl", 'orlando', 'golden heights'),
( "fl", 'miami', 'el portal')]
想知道 pandas 或任何其他將列表列表轉換為嵌套字典的庫是否有通用解決方案,或者如果有人編寫了 function 適用於多級嵌套數據,則每個集合中的元素數量可能更多,所以我需要的是不斷迭代並不斷追加直到整個列表被轉換為嵌套字典的東西
{
"tx": [
{"houston": [ "richmond", "kessler" ]},
{ "dallas": [ "lakewood", "cedars" ]},
],
"ct": [
{"hartford": ["richmond", "kessler"]},
{"new haven": ["westville"]},
],
"fl": [
{"orlando": ["parramore", "golden heights"]},
{"miami": ["el portal", 'gladview']},
]
}
您可以使用幾行代碼來完成:
from collections import defaultdict
d = defaultdict(lambda:defaultdict(list))
for x,y,z in l:
d[x][y].append(z)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.