Mark As Completed Discussion

What are Dict and List Comprehensions?

The comprehensions in Python are simple ways to create a new object from an existing object. There are several of these, including list, dict, set, and nested comprehensions. Let's focus on dict and list comprehensions.

We know that a dictionary is used to store sorted data. It utilizes keys and values (instead of indices and values like a list). Similar to how we have a specific index for a value in a list, we'll have a specific key for each value in the dictionary.

PYTHON
1first_dictionary = {
2    "key1": "value1",
3    "key2": "value2",
4    "key3": "value3",
5    "key4": "value4",
6}

The above dictionary contains four keys and four values. A key can be any number or string, and should be unique. The syntax of dict comprehension is:

PYTHON
1dict_name = {key: value for (key, value) in oldDict.items()}

Now, we will create a new dictionary from first_dictionary. We won't create a duplicate dictionary, but we'll add some values to its existing value.

PYTHON
1new_dictionary = {key: value + " new" for (key, value) in first_dictionary.items()}

This will generate the following dictionary:

PYTHON
1{"key1": "value1 new", "key2": "value2 new", "key3": "value3 new", "key4": "value4 new"}

We can accomplish this task using a loop, but it's more expensive. We can also pass any condition into comprehensions.