如何将元组转换为字典?

时间:2015-02-12 09:52:36

标签: python dictionary tuples

我有一个元组列表(每个元组有3个元素),我想把它转换成字典,如何以最有效的方式做到这一点?这是一个例子:

[(980898, 9977, 1),
 (899979879, 23, 1),
 (1, 1, 2),
 (980898, 98789797, 1),
 (98789797, 980898, 1),
 (1, 756735, 1),
 (1, 3344, 1),
 (23, 4, 1),
 (534, 23, 1),
 (756735, 1, 1),
 (9977, 980898, 1),
 (23, 899979879, 1),
 (4, 23, 1),
 (756735, 980898, 1),
 (3344, 1, 1),
 (980898, 756735, 1),
 (23, 534, 1)]

我想要以下词典:

{1: {1: 2, 3344: 1, 756735: 1},
 4: {23: 1},
 23: {4: 1, 534: 1, 899979879: 1},
 534: {23: 1},
 3344: {1: 1},
 9977: {980898: 1},
 756735: {1: 1, 980898: 1},
 980898: {9977: 1, 756735: 1, 98789797: 1},
 98789797: {980898: 1},
 899979879: {23: 1}}

这里元组的第一个元素是键,下一个元素成为第一个元素的dict中的键,最后一个元素成为第二个键的值。

我尝试了以下内容,但它提供了不完整的字典:

finalDict = {a:{b:c} for a,b,c in e}
print finalDict

{1: {3344: 1}, 980898: {756735: 1}, 4: {23: 1}, 98789797: {980898: 1}, 899979879: {23: 1}, 3344: {1: 1}, 534: {23: 1}, 23: {534: 1}, 9977: {980898: 1}, 756735: {980898: 1}}

3 个答案:

答案 0 :(得分:3)

d = [(980898, 9977, 1),
 (899979879, 23, 1),
 (1, 1, 2),
 (980898, 98789797, 1),
 (98789797, 980898, 1),
 (1, 756735, 1),
 (1, 3344, 1),
 (23, 4, 1),
 (534, 23, 1),
 (756735, 1, 1),
 (9977, 980898, 1),
 (23, 899979879, 1),
 (4, 23, 1),
 (756735, 980898, 1),
 (3344, 1, 1),
 (980898, 756735, 1),
 (23, 534, 1)]

from collections import defaultdict

D = defaultdict(dict)

for a, b, c in d:
    D[a][b] = c

for k in sorted(D):
    print k, D[k]

1 {3344: 1, 1: 2, 756735: 1}
4 {23: 1}
23 {4: 1, 534: 1, 899979879: 1}
534 {23: 1}
3344 {1: 1}
9977 {980898: 1}
756735 {1: 1, 980898: 1}
980898 {9977: 1, 98789797: 1, 756735: 1}
98789797 {980898: 1}
899979879 {23: 1}

答案 1 :(得分:2)

你的

{a:{b:c} for a,b,c in e}

会覆盖主词典的值。您可以使用setdefault访问主词典的值(如果已存在):

d = {}
for a, b, c in e:
    d.setdefault(a, {})[b] = c

答案 2 :(得分:1)

您的代码仅保留给定键的第一个遇到的值。您可以使用defaultdict模块中的collections使用新的result初始化dict,然后将密钥设置为元组列表中遇到的值。

#all_tuples = [(...), (...), ...]
from collections import defaultdict

result = defaultdict(dict)
for uid, k, v in all_tuples :
    result[uid][k] = v

dict(result)

输出:

{1: {1: 2, 3344: 1, 756735: 1},
 4: {23: 1},
 23: {4: 1, 534: 1, 899979879: 1},
 534: {23: 1},
 3344: {1: 1},
 9977: {980898: 1},
 756735: {1: 1, 980898: 1},
 980898: {9977: 1, 756735: 1, 98789797: 1},
 98789797: {980898: 1},
 899979879: {23: 1}}