Discover the Artistry of Dictionary Comprehensions in Python

Discover the Artistry of Dictionary Comprehensions in Python

Dictionary comprehensions work exactly like list comprehensions, but to construct dictionaries. There is only a slight difference in the syntax. The following example will suffice to explain everything you need to know:


# dictionary.comprehensions.p
from string import ascii_lowercase
lettermap = {c: k for k, c in enumerate(ascii_lowercase, 1)}y        


IF you print lettermap, you will see the following (we omitted the intermediate results, but you get the gist):


$ python dictionary.comprehensions.p
{'a': 1,
 'b': 2,
 ...
 'y': 25,
 'z': 26}y        

In the preceding code, we are enumerating the sequence of all lowercase ASCII letters (using the enumerate function). We then construct a dictionary with the resulting letter/number pairs as keys and values. Notice how the syntax is similar to the familiar dictionary syntax.

There is also another way to do the same thing:


lettermap = dict((c, k) for k, c in enumerate(ascii_lowercase, 1))        

In this case, we are feeding a generator expression (we’ll talk more about these later in this chapter) to the dict constructor.

Dictionaries do not allow duplicate keys, as shown in the following example

# dictionary.comprehensions.duplicates.p
word = 'Hello'
swaps = {c: c.swapcase() for c in word}
print(swaps) # prints: {'H': 'h', 'e': 'E', 'l': 'L', 'o': 'O'}y        

We create a dictionary with the letters of the string ‘Hello’ as keys and the same letters, but with the case swapped, as values. Notice that there is only one ‘l’: ‘L’ pair. The constructor doesn’t complain; it simply reassigns duplicates to the last value. Let’s make this clearer with another example that assigns to each key its position in the string:

# dictionary.comprehensions.positions.p
word = 'Hello'
positions = {c: k for k, c in enumerate(word)}
print(positions) # prints: {'H': 0, 'e': 1, 'l': 3, 'o': 4}y        

Notice the value associated with the letter ‘l’: 3. The ‘l’: 2 pair isn’t there; it has been overridden by ‘l’: 3.

That’s it for Today. See you tomorrow.



要查看或添加评论,请登录

Usama Sarwar的更多文章

社区洞察

其他会员也浏览了