I was wondering about the idiomatic way Python to initialize a dictionary with all values set to zero and the keys coming from a list. A little research gave me the idea that dict.fromkeys was a common way and certainly seems pretty succinct.
colors = ['red', 'green', 'blue']
color_scores = dict.fromkeys(colors, 0)
# {'red': 0, 'green': 0, 'blue': 0}
I was also wondering about the idiomatic to obtain a list from a lists of lists i.e. given:
fruits = [['fruit_name', 'color', 'rating'], ['jonathan apple', 'red', 63], ['gala apple', 'green', 33], ['blueberry', 'blue', 99] ]
generate
['jonathan apple', 'gala apple', 'blueberry']
or combing the dictionary initialization, generate
{'jonathan apple': 0, 'gala apple': 0, 'blueberry': 0}
This following style sat well with popular approaches from other languages but I did not know if this was very idiomatic for Python, especially when used as nested expression
fruit_names = list(map( lambda row : row[0], fruits[1:]))
fruit_scores = dict.fromkeys(list(map( lambda row : row[0], fruits[1:])), 0)
The latter line would output what we were looking for:
{'jonathan apple': 0, 'gala apple': 0, 'blueberry': 0}
I had the impression that list comprehensions was a more idiomatic in Python for list transformation, and it looks pretty good for this example below
fruit_scores = dict.fromkeys([row[0] for row in fruits[1:]], 0)
Any feedback appreciated.