python dict comprehension from list code example
Example 1: python dictionary comprehension
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
Example 2: dict comprehension python
fruits = ["apple", "banana", "cherry"]
print({f: len(f) for f in fruits})
{'apple': 5, 'banana': 6, 'cherry': 6}
Example 3: types of dict comprehension
{j:j*2 for i in range(10)}
{j:j*2 for j in range(10) if j%2==0}
{j:j*2 for j in range(10) if j%2==0 and j%3==0}
{j:(j*2 if j%2==0 and j%3==0 else 'invalid' )for j in range(10) }
Example 4: dict comprehension python
keys=['var1','var2','var3']
my_dict={key:np.zeros(10) for key in keys}