Python Forum

Full Version: Data Science
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody, i have some questions regarding the following code in python:

localWinds = {name: site.local_wind(x_i=site.initial_position[:,0], # x position

                                    y_i = site.initial_position[:,1], # y position
                                    h_i=site.initial_position[:,0]*0+70, # height
                                    ws=None, # defaults to 3,4,..,25
                                    wd=None, # defaults to 0,1,...,360
                                    ) for name, site in sites.items()}
firstly I want to know what is the function of {name:.....}? why we used it here?
secondly, for in the last line means that we set these values x_i.... for the variable of name?
lastly, site in sites.items means every item in sites will be placed in variable: Site ??
This is called dict comprehension. Usually it will result in shorter (more compact) code, but in this case, with long call of site.local_wind it is better (for readability) to use regular loop to fill in the dict.
It is equivalent to following regular loop:

localWinds = {}
for name, site in sites.items():
    localWinds[name] = site.local_wind(x_i=site.initial_position[:,0], # x position
                                       y_i = site.initial_position[:,1], # y position
                                       h_i=site.initial_position[:,0]*0+70, # height
                                       ws=None, # defaults to 3,4,..,25
                                       wd=None, # defaults to 0,1,...,360
                                       ) 
basically sites is a dict and for sites.items() will yield individual (key, value) pairs. Each tuple will be unpacked into name and site. a new dict is created with key=name and value = the result of site.local_wind() called with respective arguments