[Tutor] Square Brackets

Mats Wichmann mats at wichmann.us
Tue Sep 29 16:02:58 EDT 2020


On 9/29/20 11:17 AM, Alan Gauld via Tutor wrote:

> if user not in user_groups:
>    user_groups[user] = [groups]
> else:
>    user_groups[user].append(groups)
> 
> Now, it's unfortunate that you used groups as a name because it
> is really just the name of a single group. When you find a user
> that is not in the user_groups dict you create a new entry and
> assign the value to be [groups], that is a list containing one
> element.
> 
> If you find the same user again you append a new group name
> to that same list. Everything is fine.
> 
> However, if you remove the [] from the assignment you are
> making the value of the dictionary a single string.
> So on the second occurrence you try to append() another
> string to the first but you cannot do that since strings don't
> have an append() method. Hence you get an attribute error.

Just to add on - we keep saying this here.  You can always do quick
experiments in the interactive mode.  It's good to take an expert's word
for it, but sometimes even better to convince yourself!!!

Here's some playing to show this:

Python 3.7.9 (default, Aug 19 2020, 17:05:11)
[GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {}
>>> d["local"] = "admin"
>>> type(d["local"])
<class 'str'>
>>> d["local"].append("userA")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> d["local"] = ["admin"]
>>> type(d["local"])
<class 'list'>
>>> d["local"].append("userA")
>>> d
{'local': ['admin', 'userA']}
>>>



More information about the Tutor mailing list