Dict comprehension in python

Dict comprehension in python


Dict comprehension is useful in creating new dictionaries from existing dictionaries and iterables. Data are stored in key value pairs.

Unlike list comprehension, dictionary comprehension has same syntax but with key and value. Dictionaries are powerful built-in data structures in Python that store data as key-value pairs. Each item in dictionary are enclosed in pair of curly braces.

The syntax for dict comprehnsion is:

new_dict = {new_key:new_value for item in list}

Dict comprehension example

entence = "What is the best programming language?"

result = {word:len(word) for word in sentence.split()}