码迷,mamicode.com
首页 > 其他好文 > 详细

day②:字典的fromkeys方法

时间:2016-01-13 15:43:40      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

start

##fromkeys方法本身就是把所有的key都指向同一个对象了
>>> c=dict.fromkeys(range(5),[])                 
>>> c
{0: [], 1: [], 2: [], 3: [], 4: []}
>>> c[0].append({"B":{123}})
>>> c
{0: [{‘B‘: set([123])}], 1: [{‘B‘: set([123])}], 2: [{‘B‘: set([123])}], 3: [{‘B‘: set([123])}], 4: [{‘B‘: set([123])}]}
>>> c[0].append(1)          
>>> c
{0: [{‘B‘: set([123])}, 1], 1: [{‘B‘: set([123])}, 1], 2: [{‘B‘: set([123])}, 1], 3: [{‘B‘: set([123])}, 1], 4: [{‘B‘: set([123])}, 1]}

##怎么解决我只想修改c[0]里面的值value呢?
解决:先指向另一个列表对象
>>> c=c.fromkeys(range(5),[])                    
>>> c
{0: [], 1: [], 2: [], 3: [], 4: []}
>>> c[0]=[]
>>> c[0].append({"B":{123}}) 
>>> c
{0: [{‘B‘: set([123])}], 1: [], 2: [], 3: [], 4: []}
>>> c[0].append(1)
>>> c
{0: [{‘B‘: set([123])}, 1], 1: [], 2: [], 3: [], 4: []}
>>> 



##直接定义字典
>>> b={0: [], 1: [], 2: [], 3: [], 4: []}
>>> b[0].append({"B":{123}})
>>> b
{0: [{‘B‘: set([123])}], 1: [], 2: [], 3: [], 4: []}
>>> b[0].append(1)
>>> b
{0: [{‘B‘: set([123])}, 1], 1: [], 2: [], 3: [], 4: []}


##不用fromkeys生成一个大字典的办法
>>> c={}
>>> c
{}
>>> for i in range(5):
...     c[i]=[]
... 
>>> c
{0: [], 1: [], 2: [], 3: [], 4: []}
end




day②:字典的fromkeys方法

标签:

原文地址:http://www.cnblogs.com/binhy0428/p/5127226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!