Python create dictionary with defined key and list of values with comprehension
If I have the following list of ids:
id_numbers = ['08a592a1-5a40-46b7-b9b3-b3a1e6bfdb9f', 'a31017f7-13b4-401c-81ca-fd57042bc181']
I can add these id numbers as values of a defined key "id_numbers" in a new dictionary using the following:
catalogue_ids = {"id_numbers": []}
for item in id_numbers:
catalogue_ids["id_numbers"].append(item)
I was wondering if there is a dictionary comprehension way of doing the same thing?
Solution 1:
catalogue_ids = {"id_numbers": [item for item in id_numbers]}
Solution 2:
There's no need to use list/dictionary comprehensions. You can simply assign the id_numbers
variable to the dictionary element.
catalogue_ids = {"id_numbers": id_numbers}