标签:
定义
使用键值对,
>>> person = {"name":"keven","age":15,"gender":"male"} >>> person[‘name‘] ‘keven‘ >>> type(person) <type ‘dict‘>
字典可以原地修改,即它是可变的。
>>> dict1={} >>> id(dict1) 139736380198256 >>> dict1["name"] = "Keven" >>> id(dict1) 139736380198256 >>> dict1 {‘name‘: ‘Keven‘}
利用元组在建构字典,方法如下:
>>> name = (["first","Google"],["second","Yahoo"]) >>> website = dict(name) >>> website {‘second‘: ‘Yahoo‘, ‘first‘: ‘Google‘}
或者用这样的方法:
>>> ad = dict(name="keven", age=42) >>> ad {‘age‘: 42, ‘name‘: ‘keven‘
基本操作
• len(d),返回字典(d)中的键值对的数量
>>> city_code = {‘suzhou‘: ‘0512‘, ‘beijing‘: ‘011‘, ‘shanghai‘: ‘012‘, ‘tangshan‘: ‘0315‘} >>> len(city_code) 4
• d[key],返回字典(d)中的键(key)的值
>>> city_code["suzhou"] ‘0512‘
• d[key]=value,将值(value)赋给字典(d)中的键(key)
>>> city_code = {‘suzhou‘: ‘0512‘, ‘beijing‘: ‘011‘, ‘shanghai‘: ‘012‘, ‘tangshan‘: ‘0315‘} >>> city_code["shenzhen"]="1212" >>> city_code {‘suzhou‘: ‘0512‘, ‘beijing‘: ‘011‘, ‘shanghai‘: ‘012‘, ‘tangshan‘: ‘0315‘, ‘shenzhen‘: ‘1212‘}
• del d[key],删除字典(d)的键(key)项(将该键值对删除)
>>> del city_code["shanghai"] >>> city_code {‘suzhou‘: ‘0512‘, ‘beijing‘: ‘011‘, ‘tangshan‘: ‘0315‘, ‘shenzhen‘: ‘1212‘}
• key in d,检查字典(d)中是否含有键为 key 的项
>>> "shenzhen" in city_code True >>> "sz" in city_code False
字典也可以实现格式化字符
>>> city_code = {"suzhou":"0512", "tangshan":"0315", "hangzhou":"0571"} >>> " Suzhou is a beautiful city, its area code is %(suzhou)s" % city_code ‘ Suzhou is a beautiful city, its area code is 0512
标签:
原文地址:http://www.cnblogs.com/zydev/p/5840024.html