0

So I have this segment of code

dic = {}

for (k,v) in list:
    if k in dic.keys():
        dic[k] += [v]
    else:
        dic[k] = [v]

return dic

Is there any way I can write this in a cleaner way?

smac89
  • 39,374
  • 15
  • 132
  • 179
Izak
  • 23
  • 5

1 Answers1

1

Using defaultdict:

lst = [('a', 1), ('b', 2)]
dic = collections.defaultdict(list)
for (k, v) in lst: dic[k].append(v)

From the Examples in the docs, another way that doesn't use defaultdict is by using setdefault:

lst = [('a', 1), ('b', 2)]
dic = {}
for (k, v) in lst: dic.setdefault(k, []).append(v)

This method is said to be slower than the first

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 1
    Passing `lst` to it directly won't work the way you'd want (it just puts in all the values raw, like a normal `dict`, ignoring the `list` default aspect). You need to iterate `lst` manually and do `dic[k].append(v)` over and over. – ShadowRanger Jun 23 '21 at 01:07
  • *This method is said to be slower than the first* It depends. See [HERE](https://stackoverflow.com/questions/19629682/ordereddict-vs-defaultdict-vs-dict/19643045#19643045) – dawg Jun 23 '21 at 01:19
  • @dawg: The short version of that link is, if you always need to make the default value, and there are cheaper ways to make it with dedicated syntax (`[]` vs. `defaultdict` calling `list()`), then `setdefault` is slightly faster. But in the common case where, say, 50% or more of the inputs use the same key, or (for non-builtins) you'll have to call the constructor the same way either way, `defaultdict` is similar to or better than using `dict` with `setdefault`. The case where `setdefault` wins is rare, and the win (in the rare case) is a smaller win than the loss (in the common case). – ShadowRanger Jun 23 '21 at 02:00
  • @ShadowRanger: As stated: *It depends.* If you just want to write a throw away script with minimal data, `setdefault` is fabulous; sometimes faster. If you spend more than a little while then `defaultdict` is great too. My point is that it escapes hard rules because someone will prove you wrong as soon as you state one. – dawg Jun 23 '21 at 03:20