字典

#!/usr/bin/env python
#-*- coding: utf-8 -*-


"""
字典
"""

 

元组->字典

d = dict([('a', 1), ('b', 2), ('c', 3)])

 

d = dict('a'=1, 'b'=2, 'c=3')

 

d = {}.fromkeys(('a', 'b'), '0')  # {'a':0, 'b':0}

 

 

# d = {"name": "lee", "age": 30, "gender": "male"}
# l = len(d) # 3
# l = d["name"] # lee
# l = "name" in d # True
# del d["gender"] # {'age': 30, 'name': 'lee'}

# # keys()
# for item in d.keys():
# print(item)

# # values()
# for item in d.values():
# print(item)


# # items()
# for k, v in d.items():
# print(k, v)


# # clear(self) #清空
# d = {"name": "lee", "age": 30, "gender": "male"}
# d.clear() # {}
# print(d)


# # copy(self) # 浅拷贝
# d = {"name": "lee", "age": 30, "gender": "male"}
# dic = d.copy() # {'age': 30, 'name': 'lee', 'gender': 'male'}
# print(dic)


# # dict.fromkeys() # 根据序列创建字典,必给统一的值
# d = dict.fromkeys(["name", "age", "gender"])
# print(d) # {'name': None, 'age': None, 'gender': None}
# d = dict.fromkeys(["name", "age", "gender"], "???") # {'name': '???', 'gender': '???', 'age': '???'}
# print(d)


# # get() # 获取键对应的值
# d = {"name": "lee", "age": 30, "gender": "male"}
# v = d.get("name") # lee
# v = d.get("addr") # None
# print(v)


# # pop(self, k, d=None) #删除键值,如果没有则返回默认值d
# d = {"name": "lee", "age": 30, "gender": "male"}
# v = d.pop("gender")
# print(d, v) #{'name': 'lee', 'age': 30} male
# v = d.pop("gender","not find") #not find
# print(v)


# # setdefault(self, k, d=None) #设置键值对,如果键存在,则返回键对应的值 ,如果键不存在,则增加对应键值
# d = {"name": "lee", "age": 30}
# v = d.setdefault("gender","male")
# print(d, v) # {'age': 30, 'gender': 'male', 'name': 'lee'} male
# d = {"name": "lee", "age": 30}
# v = d.setdefault("name","Tom")
# print(d, v) # {'age': 30, 'name': 'lee'} lee


# update(self, E=None, **F) #更新字典
#d = {"name": "lee"}
#d.update(age=30, gender="male") # {'age': 30, 'name': 'lee'}
#print(d)
#d = {"name": "lee"}
#d.update({'age': 30, 'gender': 'male'}) # {'name': 'lee', 'gender': 'male', 'age': 30}
#print(d)

posted @ 2018-08-15 23:12  李小样  阅读(44)  评论(0编辑  收藏  举报