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

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.

主站蜘蛛池模板: 墨脱县| 西吉县| 潼关县| 元朗区| 潼南县| 报价| 永泰县| 高陵县| 怀柔区| 汝阳县| 凤庆县| 英吉沙县| 读书| 肃南| 姜堰市| 湘潭县| 镇宁| 措勤县| 南木林县| 瑞丽市| 田阳县| 黑龙江省| 辉南县| 黑河市| 屯门区| 张家界市| 南丰县| 岳阳市| 霸州市| 库尔勒市| 沙坪坝区| 公主岭市| 萨嘎县| 兴城市| 阿克| 龙口市| 迁安市| 贵阳市| 五大连池市| 玉树县| 桦南县|