字典
dict3这里为啥用的都是小括号 外层:dict函数的括号中层:包裹参数成迭代器,这里迭代器是元组,你也可以改成列表,如>>> d3 = dict([(1,2),(3,4),(5,6)])
内层:迭代器元素是元组,是元组的括号。 suchocolate 发表于 2020-11-2 22:27
外层:dict函数的括号
中层:包裹参数成迭代器,这里迭代器是元组,你也可以改成列表,如>>> d3 = dict([( ...
键和值的对应不是用:的吗 # 创建字典的几种方式
# 一、{key: value}
dic1 = {'one': 1, 'two': 2, 'three': 3}
print(dic1)
# 二、dict()
k = ['one', 'two', 'three']
v =
dic2 = dict(zip(k,v))
print(dic2)
dic3 = dict([('one', 1), ('two', 2), ('three', 3)])
print(dic3)
#或
dic4 = dict((('one', 1), ('two', 2), ('three', 3)))
print(dic4)
# 三、dict(key=value)
dic5 = dict(one=1, two=2, three=3)
print(dic5)
# 四、fromkeys()
dic6 = dict.fromkeys(['one', 'two', 'three'], '值') # 若不指定值,值默认为None
print(dic6)
# 还有字典推导式
ls1 = ['one', 'two', 'three']
ls2 =
dic7 = {ls1: ls2 for i in range(len(ls1))}
print(dic7)
应该是比较全的了吧,若有遗漏,欢迎补充。 本帖最后由 suchocolate 于 2020-11-3 08:24 编辑
小可爱. 发表于 2020-11-2 22:32
键和值的对应不是用:的吗
迭代器每个元素只要是能拆包成2个值,dict就能转化成字典。你的例子里使用的是第3个方式迭代器,实际就是k/v循环迭代器。
详情参考help:
页:
[1]