Reputation: 5002
I have a list of data like this
data = [['A',11],['A',22],['B',14],['C',23],['C',31],['B',12]]
I put the unique items in an other list like this:
search=[]
for item in data:
if search.count(item[0]) == 0:
search.append(item[0])
# search contains ['A', 'B', 'C']
How do I search the list data
with the list search
and produce output like?
['A', [11,22]]
['B', [14,12]]
['C', [23,31]]
Upvotes: 1
Views: 151
Reputation: 215039
You can also use a comprehension:
grouped_data = dict((x[0],list(y[1] for y in data if y[0]==x[0])) for x in data)
Note, that unlike other solutions, this one has quadratic complexity, don't use it on very large lists.
Upvotes: 1
Reputation: 213075
data = [['A',11],['A',22],['B',14],['C',23],['C',31],['B',12]]
d = {}
for k, v in data:
d.setdefault(k, []).append(v)
for item in sorted(d.iteritems()):
print list(item)
prints
['A', [11, 22]]
['B', [14, 12]]
['C', [23, 31]]
but consider keeping the d
dictionary:
{'A': [11, 22], 'B': [14, 12], 'C': [23, 31]}
It will allow you to access the values more easily.
Upvotes: 2
Reputation: 4350
Create a dictionary of key value pairs, where each key is a first element in a tuple in data (you can only have unique keys in a dictionary), and the value is a list of all items that are in tuples with the key.
map = {}
for item in data:
if map.has_key(item[0]):
map[item[0]].append(item[1])
else:
map[item[0]] = []
map[item[0]].append(item[1])
>>> map
{'A': [11, 22], 'C': [23, 31], 'B': [14, 12]}
Upvotes: 1
Reputation: 47850
I'd use a defaultdict
, like so:
from collections import defaultdict
dd = defaultdict(list)
for key, val in data:
dd[key].append(val)
# dd.iteritems() will give you your output.
Upvotes: 5
Reputation: 49886
You should use a dict for this task (or an OrderedDict if necessary). Please read the python documentation: http://docs.python.org/library/stdtypes.html#mapping-types-dict
Upvotes: 1
Reputation: 602635
Use a dictionary:
d = {}
for k, v in data:
d.setdefault(k, []).append(v)
print d
prints
{'A': [11, 22], 'C': [23, 31], 'B': [14, 12]}
You can get a list of all keys with d.keys()
.
Instead of building the list data
, it would probably be better to use a dictionary right from the start.
(Someone else will recommend a defaultdict
for this soon. I prefer a dict
in this case, but it doesn't matter too much.)
Upvotes: 6