已知一些元组,如 (a1, b1, c) (a1, b1, d) (a1, b6, v) (a2, b2, e) (a2, b3, f)
它们以 list 组织起来。
如何将该元组列表转化为 {a1: {b1: [c, d], b2: [v]}, a2: {b2: [e], b3: [f]}}的格式?
{a1: {b1: [c, d], b2: [v]}, a2: {b2: [e], b3: [f]}}
已知元组中的数据皆为 string 类型。
def register_dict(data: dict, scopes: tuple, v) -> dict: temp = data for scope in scopes[:-1]: if temp.get(scope) is None: temp[scope] = {} temp = temp[scope] a = temp.get(scopes[-1], []) a.append(v) temp[scopes[-1]] = a return data if __name__ == '__main__': ss = [ ("a1", "b1", "c"), ("a1", "b1", "d"), ("a1", "b6", "v"), ("a2", "b2", "e"), ("a2", "b3", "f") ] d = {} for s in ss: register_dict(d, s[:-1], s[-1]) print(d)
谢谢,感觉您的方法比我写的三个循环的更好。
ss = [ ("a1", "b1", "c"), ("a1", "b1", "d"), ("a1", "b6", "v"), ("a2", "b2", "e"), ("a2", "b3", "f") ] result = {} for (a, b, c) in ss: if a not in result: result[a] = {b: [c]} elif b not in result[a]: result[a][b] = [c] elif c not in result[a][b]: result[a][b].append(c) print(result)
谢谢,如果是
{"index": 0, "name": a[0], "slice": [1, 2]}, {"index": 1, "name": a[1], "slice": [1, 9]}, {"index": 2, "name": a[2], "slice": [1, 22]}
这种,index 和 name 两个 key 的值有关联,但是另一个 key 的值完全没关系,有没有简易表示的方法呢? @yiwen985 @yzx200712256