如何将元组列表转换为字典

时间:2019-05-14 15:17:31

标签: python tree

我有一个类似这样的元组列表,由于实际上不是输入文本文件排在第一位,因此未按此处所示排序。

g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9),
     ('b', 'w', 9), ('b', 'z', 6),
     ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2),
     ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15),
     ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11),
     ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)]

,并希望将其转换为

g = { 
   'a': {'w': 14, 'x': 7, 'y': 9}, 
   'b': {'w': 9, 'z': 6}, 
   'w': {'a': 14, 'b': 9, 'y': 2}, 
   'x': {'a': 7, 'y': 10, 'z': 15}, 
   'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11}, 
   'z': {'b': 6, 'x': 15, 'y': 11}, 
}

我从一个文本文件开始,其中一行中的每个元组都作为字符串-未排序:

a w 14
b w 9
x a 7
...

要获取元组列表:当前具有以下代码:

with open(filename, 'r') as reader:
    num_nodes = int(reader.readline())
    edges = []

    for line in islice(reader, num_nodes + 1, None):
        values = line.split()
        values[2] = int(values[2])
        edges.append(tuple(values))

文本文件具有以下格式:

<number of nodes>
<ID of node>
...
<ID of node>
<number of edges>
<from node ID> <to node ID> <distance>
...
<from node ID> <to node ID> <distance>

我们非常感谢您的帮助/建议。

5 个答案:

答案 0 :(得分:1)

使用itertools.groupby

from itertools import groupby
from operator import itemgetter

g_dict = {k: dict(x[1:] for x in grp) for k, grp in groupby(sorted(g), itemgetter(0))}
print(g_dict)
#{'a': {'w': 14, 'x': 7, 'y': 9},
# 'b': {'w': 9, 'z': 6},
# 'w': {'a': 14, 'b': 9, 'y': 2},
# 'x': {'a': 7, 'x': 15, 'y': 10},
# 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
# 'z': {'b': 6, 'x': 15, 'y': 11}}

答案 1 :(得分:1)

如果您不想在盒子外面使用任何东西,可以尝试:

g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9),
 ('b', 'w', 9), ('b', 'z', 6),
 ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2),
 ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15),
 ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11),
 ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)]

g_dict = {}

# Go through your list of tuples
for element in g:
    # Check if we should create a new key or not
    if not element[0] in g_dict.keys():
        # Create a new key 
        g_dict[element[0]] = {}
        # Check if we need to make a new key or not for the inner dict
        if not element[1] in g_dict[element[0]].keys():
            g_dict[element[0]][element[1]] = element[2]
    else:
        if not element[1] in g_dict[element[0]].keys():
            g_dict[element[0]][element[1]] = element[2]

print g_dict

答案 2 :(得分:0)

您可以使用defaultdict中的collections,例如

>>> g
[('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9), ('b', 'w', 9), ('b', 'z', 6), ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2), ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15), ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11), ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)]
>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> 
>>> for item in g:
...   a, b, c = item
...   d[a].update({b: c})
... 
>>> import pprint
>>> pprint.pprint(dict(d))
{'a': {'w': 14, 'x': 7, 'y': 9},
 'b': {'w': 9, 'z': 6},
 'w': {'a': 14, 'b': 9, 'y': 2},
 'x': {'a': 7, 'x': 15, 'y': 10},
 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
 'z': {'b': 6, 'x': 15, 'y': 11}}

答案 3 :(得分:0)

这是在collections模块中使用defaultdict的好例子。

from collections import defaultdict

g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9),
     ('b', 'w', 9), ('b', 'z', 6),
     ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2),
     ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15),
     ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11),
     ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)]

d = defaultdict(dict)

for k1, k2, v in g:
    d[k1].setdefault(k2, v)

d
# returns:
defaultdict(dict,
            {'a': {'w': 14, 'x': 7, 'y': 9},
             'b': {'w': 9, 'z': 6},
             'w': {'a': 14, 'b': 9, 'y': 2},
             'x': {'a': 7, 'x': 15, 'y': 10},
             'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
             'z': {'b': 6, 'x': 15, 'y': 11}})

答案 4 :(得分:0)

我认为最简单的解决方案是

new_dict = {i[0]: {j[1]:j[2] for j in g if j[0]==i[0]} for i in g}

这将导致您想要的字典。

new_dict = {'x': {'y': 10, 'a': 7, 'x': 15}, 'z': {'b': 6, 'y': 11, 'x': 15}, 'y': {'w': 2, 'a': 9, 'x': 10, 'z': 11}, 'b': {'w': 9, 'z':6}, 'w': {'b': 9, 'y': 2, 'a': 14}, 'a': {'w': 14, 'x': 7, 'y': 9}}