简体   繁体   中英

How to convert a list of tuples to a dict of dicts

I have a list of tuples like so which not ordered as shown here due to the fact that the input text file isn't ordered in the first place.

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)]

and would like to convert it to

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}, 
}

I am starting off with a text file where I have each tuple in a line as strings - not ordered:

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

To get to the list of tuples: have currently the following code:

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))

The text file has the following format:

<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>

Any help/advice is highly appreciated.

Using 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}}

If you don't want to use anything outside the box you can just try:

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

You could do this using defaultdict from collections like,

>>> 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}}

This is a good case for using defaultdict from the collections module.

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}})

I think the easiest solution would be

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

It will result in the dict you want.

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM