4

How can i prevent from adding a list into a list when using setdefault with a list type definition.

output = dict()
output.setdefault("key", []).append(["name", 1])
print output
>>> {'key': [['name', 1]]}

Desired output

>>> {'key': ['name', 1]}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user1767754
  • 23,311
  • 18
  • 141
  • 164
  • 1
    What should happen if the key is already present? – user2357112 Jun 17 '15 at 02:50
  • 1
    If the key is already present, `extend()` extends _the existing list_ for that key. You can try it by yourself, by duplicating `….setdefault(…).extend(…)`. – Eric O. Lebigot Jun 17 '15 at 02:50
  • @EOL: Yes, and that behavior may not be what's desired. I know I certainly wouldn't want to work with values of the form `['name', 2, 'name', 1, 'name', 3]`. I suspect that either the values really should be nested lists, or the code should do `output['key'] = ['name', 1]` instead of using `setdefault` at all. – user2357112 Jun 17 '15 at 03:04

1 Answers1

9

You want .extend rather than .append - the former adds a list of items to a list, the latter adds a single item - so if you pass it a list, it adds the list as a single subitem.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • It's ok to extend an empty list: `output.setdefault("key", []).extend(["name", 1])` – iForests Jun 17 '15 at 02:45
  • @user1767754 extend doesn't require any elements. It works on an empty list. In fact, the code from your question works just fine if you change `append` to `extend` and nothing else. – Amber Jun 17 '15 at 02:46
  • Ohhhh....that works! I tried it accidently with just adding an element, but it expect a list.... my bad. – user1767754 Jun 17 '15 at 02:48
  • 1
    Explicitly: `my_list = []; my_list.extend([1, 2, 3]); print my_list` gives `[1, 2, 3]`. – Eric O. Lebigot Jun 17 '15 at 02:49
  • 1
    @user1767754 You can learn more about `extend` and `append` in this SO question [Python - append vs. extend](http://stackoverflow.com/questions/252703/python-append-vs-extend) – Bhargav Rao Jun 17 '15 at 02:49