dict() constructor and dict lite

2017-06-02  本文已影响0人  cutelittlePanda

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

上一篇 下一篇

猜你喜欢

热点阅读