dict() constructor and dict literal

dict() constructor builds dictionaries directly from sequences of key-value pairs, or can be used to create dictionaries from arbitrary key and value expressions; sometimes, when the keys are simple strings, it's easier to specify pairs using keyword arguments:

three ways to build dictionaries

A dict literal is created by surrounding a key-value list with{}'s; a keys is separated from its value with:'s, and thekey:valuepairs are separated with commas (,). An emptydictis simply{}.

Examples:

                 dict_li = {"name": "Danniel", "class": "class 1", "age": 6, "boy": "yes"}

                  dict_li2 = {(6,6): "blue pair", (2,5,3): " red traingle", "pentagon":["white","big,"building"]}

                  dict_li3 = {}

#1. the difference between dict literal and dict() constructor:

1). dict literal, key-value paries:   

def literal():

                 d = {'first': 1, 'second': 2}

def constructor():

                 d = dict(first = '1', second='2')

Using dis module to analyze the implementation details of CPython interpreter:

literal is little bit faster, cause it uses optimized BUILD_MAP and STORE_MAP opcodes rather than generic CALL_FUNCTION.


dis.dis(dict) disassembling.

Example of dict() usage: dict.items(), dict.get(key, 0), dict.keys(), dict.values()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容