Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: tuple of dictionary to Dictionary

How can I convert tuple of dictionaries like example present below:

({(1, 2): 3},
 {(1, 3): 5},
 {(1, 4): 5},
 {(2, 4): 5},
 {(1, 5): 10},
 {(2, 6): 9},
 {(1, 6): 9},
 {(2, 1): 2},
 {(2, 2): 3},
 {(2, 3): 5},
 {(2, 5): 10},
 {(1, 1): 2})

to a rather simpler form like dictionary:

{(1, 1): 2,
 (1, 2): 3,
 (1, 3): 5,
 (1, 4): 5,
 (1, 5): 10,
 (1, 6): 9,
 (2, 1): 12,
 (2, 2): 7,
 (2, 3): 7,
 (2, 4): 3,
 (2, 5): 4,
 (2, 6): 2}
like image 908
abhiieor Avatar asked Jan 04 '23 03:01

abhiieor


2 Answers

You can't use a dict merge comprehension (yet), but you can go via a chain map:

>>> from collections import ChainMap
>>> dict(ChainMap(*dicts))
{(1, 1): 2,
 (1, 2): 3,
 (1, 3): 5,
 (1, 4): 5,
 (1, 5): 10,
 (1, 6): 9,
 (2, 1): 2,
 (2, 2): 3,
 (2, 3): 5,
 (2, 4): 5,
 (2, 5): 10,
 (2, 6): 9}

Note: collections.ChainMap is new in Python 3.3.

It's actually a subclass of collections.Mapping, so depending on the use-case you might not even need to convert back to a plain dict.

like image 57
wim Avatar answered Jan 14 '23 02:01

wim


just iterate on the tuples and rebuild the dictionary "flat" using a dictionary comprehension:

a = ({(1, 2): 3},
 {(1, 3): 5},
 {(1, 4): 5},
 {(2, 4): 5},
 {(1, 5): 10},
 {(2, 6): 9},
 {(1, 6): 9},
 {(2, 1): 2},
 {(2, 2): 3},
 {(2, 3): 5},
 {(2, 5): 10},
 {(1, 1): 2})

b = {k:v for t in a for k,v in t.items()}

print(b)

result:

{(1, 2): 3, (2, 6): 9, (2, 1): 2, (1, 1): 2, (1, 5): 10, (1, 3): 5, (1, 6): 9, (1, 4): 5, (2, 2): 3, (2, 3): 5, (2, 5): 10, (2, 4): 5}
like image 30
Jean-François Fabre Avatar answered Jan 14 '23 03:01

Jean-François Fabre