标签:parent attach -o oat too imp weight 1.5 images
格式:dict = {key: value}
变量 = set(list); ---> s = set([1, 2, 4])
注:dict、set的key必须是不可变对象。
区别:1、dict有value,set没有
2、set可以做交集&,并集| 运算,dict 不能
一、dirct
#!/usr/bin/python
#initialize
dict = {'you':95, 'love':20, 'me':5}; # 若存在dict = {'you', 'love':, :8} 格式是错误的,key:value要配齐
print dict;
print dict['love'];
#add a key
dict['too'] = 1;
print dict;
#delete a key, its value also delete
dict.pop('love');
print dict;
#a way of check in dict
print 'you' in dict; #格式:key in dict;
#other way of check in dict
print dict.get('haha'); #当key不存在,默认返回None ,若存在返回value
print dict.get('haha', -1); #当key不存在,-1为指定的返回值
print dict.get('you', 1);
二、set
#!/usr/bin/python
#initialize
s = set([1, 2, 3, 4, 4]); #key重复会自动合并
print s;
#add
s.add(5);
print s;
#delete
s.remove(4);
print s;
# & / |
s1 = set([1, 2, 3]);
s2 = set ([2, 4, 5]);
s3 = s1 & s2;
print s3;
print s1 | s2;
list = ['y', 'o', 'u', 'l', 'o'];
q = set(list);
print q;
tuple = ('1', '2', '3');
x = set(tuple);
print x;
#error way
tuple = ('1', '2', '3');
x = set(tuple);
print x;
可见set并不支持混合的key。
标签:parent attach -o oat too imp weight 1.5 images
原文地址:http://blog.51cto.com/13502993/2142600