Python字典是一种映射类型,它的元素是键值对,键和值用冒号分隔。字典是无序的,可以使用以下八种方式来创建字典:
dict = {}
dict = dict()
dict = dict(key1=value1, key2=value2, key3=value3)
dict = dict(key1=value1, key2=value2, key3=value3)
dict = dict([(key1, value1), (key2, value2), (key3, value3)])
keys = ['key1', 'key2', 'key3'] values = [value1, value2, value3] dict = dict(zip(keys, values))
dict = {key: value for (key, value) in iterable}
dict = dict.fromkeys(keys, value)
以上就是Python创建字典的八种方式,每种方式都有其优缺点,根据实际情况选择合适的方式使用即可。
本文链接:http://task.lmcjl.com/news/8574.html