'Python beginner syntax explain
I am trying to analyze a source code on Github. I do not understand the syntax in like 86, which is circled in red. I think that dict generates the most frequent elements of Scopus based on the value of num_tokens. But I do not understand the next line and I cannot print it out because dict seems like a function. Could anyone help me to explain?
Link of the code: link 161
https://github.com/VU-DETAIL/MoleHD/blob/c3243624ab5f2b708e8ae0e01ede6ae437ab1bf5/utils.py#L173
Appreciate!
Solution 1:[1]
Dictionary Comprehension means that when traversing the dictionary if you find an item that satisfies the structure you have written, you keep the value of that item to form a new dictionary, e.g.
If dict is a dictionary like this.
dict = {"a": 1, "bc": 2, "cba": 3}
Then each item returned when using the enumerate function is [index, key of the dictionary],like:
[(0, 'a'), (1, 'bc'), (2, 'cba')]
So the following two pieces of code are equivalent
dict = {x[0]: 1 for i, x in enumerate(dict)}
# Equivalent to
dic = {}
for i, x in enumerate(dict):
dic[x[0]] = 1
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 | maya |

