'Python variable type change on the same line
It is probably a simple question, but I am always confused about it. Here is the code
routes = {}
for line in file:
match = gig_pattern.search(line)
if match:
intf = match.group(2)
routes[intf] = routes[intf]+1 if intf in routes else 1
on the left of the equal sign routes[intf] means add an item in the routes dictionary. on the right of the equal sign, how can the routes[intf] become an integer? Any explaination is welcome or url for existing explaination.
Solution 1:[1]
The difference is not the square brackets, but the equals sign.
Square brackets tell python to look for a value at a certain position in a list or dictionary:
> list_or_dict[key]
1
On its own, like this, python returns the value or throws an error if it can't find it.
However, if you follow this with an equals sign python instead assigns the value on the right of the equals sign to the key specified in the dictionary on the left:
> list_or_dict[key] = 2
> list_or_dict[key]
2
So the presence of the equals sign determines whether the square brackets will fetch a value or assign a value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ari Cooper-Davis |
