官术网_书友最值得收藏!

  • Mastering Python
  • Rick van Hattem
  • 194字
  • 2021-07-16 11:10:34

dict comprehensions

dict comprehensions are very similar to list comprehensions, but the result is a dict instead. Other than this, the only real difference is that you need to return both a key and a value, whereas a list comprehension accepts any type of value. The following is a basic example:

>>> {x: x ** 2 for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

>>> {x: x ** 2 for x in range(10) if x % 2}
{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}

Note

Since the output is a dictionary, the key needs to be hashable for the dict comprehension to work.

The funny thing is that you can mix these two, of course, for even more unreadable magic:

>>> {x ** 2: [y for y in range(x)] for x in range(5)}
{0: [], 1: [0], 4: [0, 1], 16: [0, 1, 2, 3], 9: [0, 1, 2]}

Obviously, you need to be careful with these. They can be very useful if used correctly, but the output quickly becomes unreadable, even with proper whitespace.

主站蜘蛛池模板: 曲靖市| 乌拉特中旗| 乐安县| 长子县| 肃宁县| 格尔木市| 蒲城县| 阿坝县| 天峨县| 平湖市| 东乡| 昌邑市| 澎湖县| 营山县| 定兴县| 通江县| 彩票| 仙居县| 轮台县| 甘南县| 威信县| 定州市| 苍南县| 咸宁市| 沾化县| 岗巴县| 甘谷县| 若羌县| 萨嘎县| 简阳市| 临漳县| 蚌埠市| 治县。| 遵义市| 汉源县| 新邵县| 锦屏县| 大邑县| 宁陵县| 韶关市| 延寿县|