Kim Stacks
Kim Stacks

Reputation: 10812

Is there a more Pythonic way to loop through a list and then have each loop variable update a dictionary?

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 :

  1. Map returns a list
  2. Filter reduces the number of elements
  3. Reduce looks like it will return the native data type within the list. Maybe string or number depending on the original list.

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

Answers (2)

Daniel H
Daniel H

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

viraptor
viraptor

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

Related Questions