[Tutor] Square Brackets
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Sep 29 13:17:53 EDT 2020
On 29/09/2020 16:19, P L wrote:
> if I remove the square brackets from groups, it affects the else statement and I don't know why.
> You get an attribute error message.
If you want to discuss an error message always include the full error
message text. Otherwise we have to guess.
> I figure the error message should be under the if statement and not the else statement.
Error messages often appear later in the code that the point of the
error. The interpreter generates the error only once it realizes that
something is wrong, which may not be at the point where the actual
error occurs.
The other problem we have in commenting is that you have lost all
indentation in the mail process. You need to post in plain text(not
HTML) format to keep the indentation. So its not clear to us where the
else is aligned. Is it part of the if or part of (one of) the for loop?
Now, having said that I'll make some guesses about the problem:
> def groups_per_user(group_dictionary):
> user_groups = {}
> for groups, users in group_dictionary.items():
> for user in users:
> if user not in user_groups:
> user_groups[user] = [groups]
> else:
> user_groups[user].append(groups)
>
> return(user_groups)
>
> print(groups_per_user({"local": ["admin", "userA"],"public": ["admin", "userB"],
> "administrator": ["admin"] }))
I'll assume this is the code that you are talking about:
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.
And the error occurs in the else part, it has nothing to
do with the if part which is perfectly valid python code.
So the interpreter is correct in telling you that there
is an attribute error - strings have no append() method
And it is correct in saying the problem is in the else
part not the if part.
Its up to you to understand what you wanted to do and realize
that you needed to add a single valued list in the if part,
not a single string. Python is not clever enough to understand
what you intended, it can only read what you actually wrote.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list