LucSpan
LucSpan

Reputation: 1971

Convert tuple containing tuple into dictionary

Set-up

I have a list containing tuples, each which contains a tuple.

Part of the list,

l = [ ('E', ('1058GK', '1058GK')),
      ('K', ('1058GL', '1058GN')),
      ('E', ('1058GP', '1058HC')),
      ('K', ('1058HD', '1058LT'))]

Problem

I want to convert l to a dictionary such that,

d = {'E': ['1058GK','1058GK','1058GP','1058HC'],
     'K': ['1058GL','1058GN','1058HD','1058LT']}

How would I go about?


Tried

d = {k:v for k,v in l} brings me close, but this would create,

d = {'E': ('1058GP','1058HC'),
     'K': ('1058HD','1058LT')}

Upvotes: 2

Views: 256

Answers (4)

hiro protagonist
hiro protagonist

Reputation: 46849

you could use setdefault:

d = {}
for key, lst in l:
    d.setdefault(key, []).extend(lst)

# results in
# d = {'E': ['1058GK', '1058GK', '1058GP', '1058HC'], 
#      'K': ['1058GL', '1058GN', '1058HD', '1058LT']}

if the key is not in the dictionary already, it will be added, containing an empty list. the list is then extended with the elements in the corresponding tuples.


or you could use a defaultdict:

from collections import defaultdict

d = defaultdict(list)

for key, lst in l:
    d[key].extend(lst)

Upvotes: 2

Ilario Pierbattista
Ilario Pierbattista

Reputation: 3265

I think this is ok

d = {k:[] for (k, v) in l}
for (k, v) in l:
    d[k] += list(v)
print(d)

First it allocates a dictionary of empty lists. Then is iterates over the elements of l casting tuples to lists and merging them with respect to the keys k.

Upvotes: 0

Thomas Kühn
Thomas Kühn

Reputation: 9810

As the keys in your original list can occur several times, it is best to loop through your list. You can go through your list element wise and right away split the outer tuple into key-element pairs like so:

l = [ ('E', ('1058GK', '1058GK')),
      ('K', ('1058GL', '1058GN')),
      ('E', ('1058GP', '1058HC')),
      ('K', ('1058HD', '1058LT'))]
mydict = {}
for key, tup in l:
    try:
        mydict[key]+=list(tup)
    except KeyError:
        mydict[key]=list(tup)

print(mydict)

the try-except block makes sure that the different keys really exist within mydict and if they don't, creates them accordingly.

Upvotes: 0

mohammad
mohammad

Reputation: 2198

l = [ 
    ('E', ('1058GK', '1058GK')),
    ('K', ('1058GL', '1058GN')),
    ('E', ('1058GP', '1058HC')),
    ('K', ('1058HD', '1058LT'))
]
res = dict()
for elem in l:
    res[elem[0]] = res.get(elem[0], []) + list(elem[1])

Upvotes: 0

Related Questions