dictionary comprehensions code example

Example 1: create dictionary comprehension python

{key:value for key in iterable}

Example 2: dict comprehension python

# dict comprehension we use same logic, with a difference of key:value pair
# {key:value for i in list}

fruits = ["apple", "banana", "cherry"]
print({f: len(f) for f in fruits})

#output
{'apple': 5, 'banana': 6, 'cherry': 6}

Example 3: dictionary comprehension python

print({i:j for i,j in zip(txt_list,num) if i!="All"})

Example 4: dict comprehension python

keys=['var1','var2','var3']
my_dict={key:np.zeros(10) for key in keys}

Example 5: dictionary comprehension

li = ['The', 'quick', 'brown', 'fox', 'was', 'quick']d = {k:1 for k in li}d #=> {'The': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'was': 1}