Day 40: Create Dictionary Comprehension

Create Dict Comprehensions

There are many other objects you can build using comprehensions, such as dictionaries, pervasive objects in Data Science. Main difference between a list comprehension and a dict comprehension is the use of curly braces {} instead of []. Additionally, members of the dictionary are created using a colon (:) as in <key> : <value> as the output expression.

The syntax:

[output expressionforiterator variableiniterable].

DataCamp’s example:

Another sample code I extracted from DataCamp’s tutorial to output the fellowship’s name and its length in key-value pair.

# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']

# Create dict comprehension: new_fellowship
new_fellowship = {key: len(key)  for key in fellowship}

# Print the new list

#Output: {'frodo': 5, 'samwise': 7, 'merry': 5, 'aragorn': 7, 'legolas': 7, 'boromir': 7, 'gimli': 5}

Summary of the day:

  • Dict comprehensions.
  • Dict comprehensions vs list comprehensions.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s