user2350962
user2350962

Reputation: 11

trying to make sense of a Python code

I have a question about the logic of a Python code I've found online that works brilliantly to define a dict from a list formatted in pairs (ie: "one 1/n two 2/n three 3/n") The code is:

dict_number= {term:int(score) for (term,score) in list_number}

List_number is the list where the values are held, I am not sure I understand how Python understands that everyodd string should be assigned as term and everyeven as a value(well in this case the int of that string)... both term and score have not being defined before this line of code and somehow python manages to make sense of this... any idea how this works?

Upvotes: 0

Views: 93

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174614

This is called a dictionary comprehension and was introduced in Python 2.7. It is a shorthand way of creating dictionaries by using expressions.

The longer way of writing that line is:

dict_number = {}  # an empty dictionary

for term,score in list_number:
    dict_number[term] = int(score)

In Python, there are no variables as what you may be used to from other languages. In most other languages, a variable is a "box" that can hold a specific type of value. To hold something in the box, first you have to create the box by describing the type:

int x;
x = 1;

Python has the concept of names that point to values. A "variable" in python is simply a name, that can point to any value at any type. Only values have types, names don't have types. Due to that flexibility, names don't have to be "initialized" in advance. You simply use them when you need them; and Python will take care of the rest.

Upvotes: 3

Related Questions