1. 程式人生 > >鏈表:dict

鏈表:dict

-o dir form nbsp love ict auto title wrap

格式:

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。





鏈表:dict