Reputation: 10812
I am trying to write a more pythonic or a more concise way and avoid writing too many for loops.
Basically I have the following block code:
result = {}
for model_name in list_of_model_names:
model_fields = _do_something(model_name)
result['{}_fields'.format(model_name)] = model_fields
return result
In essence, I am looping through a list of strings. Each string I will perform some action so that some derivative of that string becomes a key and value pair in a dictionary.
I am reading through http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html
I know that :
My code is working, I was wondering if there's a more concise or a more pythonic way to loop through a list and have its loop variable affect the key and value of a dictionary.
Upvotes: 0
Views: 57
Reputation: 7443
Generally, the more Pythonic way is not to use map
, filter
, and reduce
, but to use comprehensions.
For your code, that would be
result = {'{}_fields'.format(model_name): _do_something(model_name)
for model_name in list_of_model_names}
Comprehensions can also work for lists and sets.
Upvotes: 2
Reputation: 34155
You can be more concise using:
result = {(name+'_fields'): _do_something(name) for name in list_of_model_names}
Whether that's more readable, or useful is up to you though.
Upvotes: 2