美文网首页
dict() constructor and dict lite

dict() constructor and dict lite

作者: cutelittlePanda | 来源:发表于2017-06-02 20:29 被阅读0次

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()

相关文章

网友评论

      本文标题:dict() constructor and dict lite

      本文链接:https://www.haomeiwen.com/subject/wciufxtx.html