0

The title describes the problem, this is what i tried and this is not giving me expected resoult.. where is the problem?

for name in file:              
  if name in list:
    if dict.has_key(param):
      dict[param] = [dict[param],name]
    else:
      dict[param] = name

expecting output:

dict = {
'param1': ['name11', 'name12', 'name13'],
'param2': ['name21', 'name22', 'name23'],
.
.
.
}
Pythonizer
  • 1,080
  • 4
  • 15
  • 25

2 Answers2

3

You need to append these names to a list. The following is a naive example and might break.

for name in file:              
    if name in list:
        if dict.has_key(param):
            dict[param].append(name)
        else:
            dict[param] = [name]

Or if you want to be a little cleaner, you can use collections.defaultdict. This is the pythonic way if you ask me.

d = collections.defaultdict(list)
for name in file:
    if name in lst: # previously overwrote list()
        d[param].append(name)

Please do not overwrite the builtin dict() or list() function with your own variable.

msvalkon
  • 11,887
  • 2
  • 42
  • 38
  • I thought that append doesn't work with dicts, at least it gave me an error while i was trying this but now it works, maybe because i didn't try to use append after `else` condition – Pythonizer Apr 04 '14 at 11:48
  • 1
    @Streak the `else` clause wraps `name` in `[]`, thus turning it into a list containing a single element. It's not very pretty, I would use the second solution. – msvalkon Apr 04 '14 at 11:49
  • 1
    I'd also add, please *do not* overwrite the builtin `list()` function with your own variable – Javier Apr 04 '14 at 11:59
  • For the first answer, you can avoid the `else` and the hack using the `.get` method, but using `defaultdict` is the preferred pythonic way. – Javier Apr 04 '14 at 12:01
  • @Javier I feel that's *slightly* hackish as well. I would direct everyone to use the defaultdict, or maybe add an example with `dict.setdefault`. – msvalkon Apr 04 '14 at 12:04
  • 1
    @msvalkon totally agree, that is precisely what `defaultdict` was introduced for. I'd only use the get trick if I had to deal with an object that has been defined somewhere else; e.g. if the dict comes as the output from a mongodb query. – Javier Apr 04 '14 at 12:09
0

You are looking for a multi map, i.e. a map or dictionary which does not have a key -> value relation but a key -> many values, see:

See Is there a 'multimap' implementation in Python?

Community
  • 1
  • 1