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?
1 Answer 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
-
This is exactly what is needed! Thank you very much! Can you give a brief explanation about why that works or what it does?Schattener– Schattener05/06/2022 16:35:03Commented May 6, 2022 at 16:35
-
The asterisk is an unpacking operator in this contextRamrab– Ramrab05/06/2022 16:36:27Commented May 6, 2022 at 16:36
-
Much appreciated @LancelotduLac, that's what I was wondering about!Schattener– Schattener05/06/2022 16:38:06Commented 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~BeRT2me– BeRT2me05/06/2022 16:42:12Commented May 6, 2022 at 16:42 -
Understood, I'll go over that article, thanks again @BeRT2me!Schattener– Schattener05/06/2022 16:48:19Commented May 6, 2022 at 16:48
lang-py
admin_access
={'allowed_users': [['user1', 'user2', 'user3'], 'adminuser1', 'adminuser2']}
{'allowed_users': ['user1', 'user2', 'user3', 'adminuser1', 'adminuser2']}
or above