Q:

merging sublists within a list sharing common index element

I have a list like:
loc_list=[['1,', "'Houston'"], 
         ['4,', "'Stafford'"], 
         ['5,', "'Bellaire'"], 
         ['5,', "'Sugarland'"], 
         ['5,', "'Houston'"], 
         ['6,', "'Atlanta'"], 
         ['6,', "'Sacramento'"], 
         ['7,', "'Milwaukee'"], 
         ['8,', "'Chicago'"], 
         ['8,', "'Dallas'"], 
         ['8,', "'Philadephia'"], 
         ['8,', "'Seattle'"], 
         ['8,', "'Miami'"], 
         ['9,', "'Arlington'"], 
         ['11,', "'Austin'"]]

Now I want to merge the list having same element at first position.
Desired_list=[['1,', "'Houston'"], 
             ['4,', "'Stafford'"], 
             ['5,', "'Bellaire','Sugarland','Houston'"],
             ['6,', "'Atlanta','Sacramento'"],
             ['7,', "'Milwaukee'"], 
             ['8,', "'Chicago','Dallas','Philadephia','Seattle','Miami'"], 
             ['9,', "'Arlington'"], 
             ['11,', "'Austin'"]]

I'm clueless.

A:

You'd be better off with a dict-like structure, defaultdict with set would seem the best choice.
Here's an example:
>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> for index,city in loc_list:
...   d[index].add(city)
... 
>>> for k,v in d.items():
...   print(k,v)
... 
4, {"'Stafford'"}
6, {"'Atlanta'", "'Sacramento'"}
1, {"'Houston'"}
5, {"'Houston'", "'Bellaire'", "'Sugarland'"}
9, {"'Arlington'"}
8, {"'Philadephia'", "'Dallas'", "'Seattle'", "'Chicago'", "'Miami'"}
7, {"'Milwaukee'"}
11, {"'Austin'"}

BTW: Your input list looks a bit strange, the keys are strings (instead of numbers) with a trailing coma: '4,'; and the values have double quotes: "'Chicago'".

