练习40——字典, 可爱的字典

感谢Runoob的教程:
http://www.runoob.com/python3/python3-dictionary.html

*更多功能的参考来自runoob

# -*- coding: utf-8 -*-
# 练习40:字典, 可爱的字典

# ******教材内容******
class Song (object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def  sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

happy_bday = Song(["Happy birthday to you", 
                   "I don't want to get sued",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

# ******字典功能拓展******
# Do More Exercise of Dictionary

# Make a new empty dict
myDict = {}

# Or give it something
myDict = {'a1': 'Mike','a2': 'Jack','a3': 'Luck'}

# Now,read something of dict
stuff_1 = myDict['a1']
stuff_2 = myDict['a2']
print ("a1:" +stuff_1, "\na2:" +stuff_2)

# If want to show something not in dictionary
#stuff_4 = myDict['a4']  #-->will show error:
#print ("a4:" + stuff_4) #Traceback (most recent call last):
                         #[Finished in 0.1s with exit code 1]  File "C:\PE\ex40.py", line 40, in <module>
                         #    stuff_4 = myDict['a4']
                         #KeyError: 'a4'


# try to change something
myDict['a1'] = 'Mike_af'
print ("now a1 is:" + myDict['a1'])

# try to delete something
del myDict['a1']    # 删除key为'a1'的条目
Mydict.clear()      # 清空dictionary所有条目
del myDict          # 删除dictionary
#print (myDict['a1'])   #-->will show error:
                        #   File "C:\PE\ex40.py", line 53, in <module>
                        #     print (myDict['a1'])
                        # KeyError: 'a1'
## -*- coding: utf-8 -*-
#更多的字典操作命令

#cmp(dict1, dict2) python3已删除该功能

#len(dict) 返回字典元素总数
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
len(dict) # --> return 3

#str(dict) 输出字典可以打印的字符串表示
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
str(dict) # --> return {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

#type(variable ) type变量,如果是字典就返回字典类型
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
type(dict) # --> return <class 'dict'>

#dict.clear() 删除字典内所有元素
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.clear() # --> {}

#dict.copy() 返回一个dict的副本
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict1 = dict 
dict2 = dict.copy()

del dict['Name']
print (str(dict1)) # --> {'Class': 'First', 'Age': 7}
print (str(dict2)) # --> {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
                   # 使用直接赋值 dict1 = dict 时,dict1的值回随着dict的变化而变化。
                   # 而使用copy()方法时,会生成一个独立的副本,从下面的内存地址也可以看出其中区别。
print (id(dict))  # --> 6302896
print (id(dict1)) # --> 6302896
print (id(dict2)) # --> 6302696

#dict.fromkeys(seq[,value]) 创建一个新字典,以学列seq中元素做字典的键,val为字典所有键对应的初始值
seq = {'a', 'b', 'c'}
dict.fromkeys(seq)      # --> {'b': None, 'c': None, 'a': None}
dict.fromkeys(seq, 10)  # --> {'b': 10, 'c': 10, 'a': 10}

#dict.get(key, default=None) 返回指定键的值,如果没有则返回default值
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.get('Name')            # --> 返回Runoob,键区分大小写
dict.get('Not_in_Dict')     # --> 返回None
dict.get('Not_in_Dict', 1)  # --> 返回1

# key in dict如果键在字典dict里返回true,否则返回false
# python2 下该方法名为dict.has_key(key) 
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
'Name' in dict          # --> return True
'Not_in_Dict' in dict   # --> return False

#dict.items() 以列表返回可遍历的(键, 值) 元组数组
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.items()    # --> dict_items([('Age', 7), ('Class', 'First'), ('Name', 'Runoob')])

#dict.keys() 以列表返回一个字典所有的键
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.keys()     # --> dict_keys(['Class', 'Age', 'Name'])

#dict.setdefault(key[,default=None]) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.setdefault('Name')                     # --> return Runoob
dict.setdefault('Not_in_Dict')              # --> return None,set a new key, key = None
dict.setdefault('Not_in_Dict', 'A_new_Key') # --> return None,set a new key, key = A_new_Key

#dict.update(dict2) 把字典dict2的键/值对更新到dict里
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict2 =  {'Name': 'Runoob_2', 'Age': 14, 'Class': 'First_2'}
dict.update(dict2)  # --> {'Class': 'First_2', 'Name': 'Runoob_2', 'Age': 14}

#dict.values() 以列表返回字典中的所有值
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict.values()   # --> dict_values([7, 'Runoob', 'First'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值