python:字典
字典(dictionary)是除列表之外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取,这个键可以是数字、字符串甚至元组。映射可以使用任何不可变对象标识元素,最常用的类型是字符串和元组,python唯一内建的映射类型是字典。
语法:
>>> info = { ... 'stu1101': "TengLan Wu", ... 'stu1102': "LongZe Luola", ... 'stu1103': "XiaoZe Maliya", ... }
字典的特性:
- dict是无序的
- key必须是唯一的,天生去重
增加
>>> info["stu1104"] = "wangzhaoyang" >>> info {'stu1101': 'TengLan Wu', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'wangzhaoyang'}
修改
>>> info["stu1101"] = "ligang" >>> info {'stu1101': 'ligang', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'wangzhaoyang'}
删除
>>> info {'stu1101': 'ligang', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'wangzhaoyang'} >>> info.pop("stu1102") #常用删除方法 'LongZe Luola' >>> info {'stu1101': 'ligang', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'wangzhaoyang'} >>> del info["stu1103"] >>> info {'stu1101': 'ligang', 'stu1104': 'wangzhaoyang'}
>>> info
{'stu1101': 'ligang', 'stu1104': 'wangzhaoyang', 'stu1102': 'zhanglei'}
>>> info.pop
info.pop( info.popitem(
>>> info.popitem() ###随机删除
('stu1102', 'zhanglei')
>>> info
{'stu1101': 'ligang', 'stu1104': 'wangzhaoyang'}
查找
>>> info {'stu1101': 'ligang', 'stu1104': 'wangzhaoyang', 'stu1102': 'zhanglei', 'stu1103': 'liyang'} >>> "stu1102" in info True >>> info.get("stu1101") 'ligang' >>> info.get("stu1105") ##get查找,如果存在则返回,不存在不会报错 >>> info["stu1101"] 'ligang' >>> info["stu1105"] #存在则返回,不存在则报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'stu1105'
items #将一个字典转换为元组
>>> info.items() dict_items([('stu1101', 'ligang'), ('stu1104', 'wangzhaoyang'), ('stu1102', 'zhanglei'), ('stu1103', 'liyang')])
key values
#values >>> info.values() dict_values(['LongZe Luola', 'XiaoZe Maliya']) #keys >>> info.keys() dict_keys(['stu1102', 'stu1103'])
多级嵌套
people ={ 'Jason':{ 'phone':'2341', 'addr':'Foo drive 23' }, 'James':{ 'phone':'4564', 'addr':'Bar street 42' }, 'Jzhou':{ 'phone':'4564', 'addr':'Baz avenue 90' } }
people["James"]["phone"] = "10000" >>> people {'Jason': {'phone': '2341', 'addr': 'Foo drive 23'}, 'James': {'phone': '10000', 'addr': 'Bar street 42'}, 'Jzhou': {'phone': '4564', 'addr': 'Baz avenue 90'}}
循环字典
#方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v)
将字典key-value翻转
a={1:10,2:20,3:30} b={v:k for k,v in a.items()} # 第二种方法 dict(map(reversed, a.items()))