1

In building a config file, I'm trying to add a list to another list. I'd rather not use any functions like append or python logic in this config file. Some examples are listed below:

config = {
 'users': [
 'user1',
 'user2',
 'user3'
 ]
}
admin_access = {
 'allowed_users': [
 config['users'],
 'adminuser1',
 'adminuser2'
 ]
}

Am I going about this the right way or am I completely off?

asked May 6, 2022 at 16:25
5
  • What output do you want? Commented May 6, 2022 at 16:27
  • 1
    This kind of looks like it would be working Commented May 6, 2022 at 16:27
  • 1
    Why not just run your code and look at the output... Here admin_access = {'allowed_users': [['user1', 'user2', 'user3'], 'adminuser1', 'adminuser2']} Commented May 6, 2022 at 16:28
  • Are you want this output {'allowed_users': ['user1', 'user2', 'user3', 'adminuser1', 'adminuser2']}or above Commented May 6, 2022 at 16:30
  • Solution found by @BeRT2me via the * prefix operator which unpacks the list! Commented May 6, 2022 at 16:37

1 Answer 1

1

I think what you may be looking for is:

admin_access = {
 'allowed_users': [
 *config['users'],
 'adminuser1',
 'adminuser2'
 ]
}

Which gives:

{'allowed_users': ['user1', 'user2', 'user3', 'adminuser1', 'adminuser2']}

If you couldn't directly create admin_access like this, you could also add on the wanted list like this:

# Given
config = {'users': ['user1', 'user2', 'user3']}
admin_access = {'allowed_users': ['adminuser1', 'adminuser2']}
# Do
admin_access['allowed_users'] += config['users']
# Outputs
print(admin_access)
{'allowed_users': ['adminuser1', 'adminuser2', 'user1', 'user2', 'user3']}
answered May 6, 2022 at 16:30
5
  • This is exactly what is needed! Thank you very much! Can you give a brief explanation about why that works or what it does? Commented May 6, 2022 at 16:35
  • The asterisk is an unpacking operator in this context Commented May 6, 2022 at 16:36
  • Much appreciated @LancelotduLac, that's what I was wondering about! Commented May 6, 2022 at 16:38
  • A lot of places only reference the * operator in the context of functions, but this article Does a good job of explaining it in the context of lists and dicts as well~ Commented May 6, 2022 at 16:42
  • Understood, I'll go over that article, thanks again @BeRT2me! Commented May 6, 2022 at 16:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.