Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of tuples into a dict

I have a list of tuples like this:

[ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] 

I want to iterate through this keying by the first item, so, for example, I could print something like this:

a 1 2 3 b 1 2 c 1 

How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...

like image 309
Dan Avatar asked Nov 04 '08 12:11

Dan


People also ask

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can we use list of tuple as key in dictionary?

A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.


2 Answers

l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ]  d = {} for x, y in l:     d.setdefault(x, []).append(y) print d 

produces:

{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]} 
like image 76
Ned Batchelder Avatar answered Sep 20 '22 02:09

Ned Batchelder


Slightly simpler...

from collections import defaultdict  fq = defaultdict(list) for n, v in myList:     fq[n].append(v)      print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}) 
like image 41
S.Lott Avatar answered Sep 23 '22 02:09

S.Lott