Wildwolf1995

Python笔记4——字典的一些基本操作

 

#字典  key-value
#添加
my_family= {"father": "weihaiqing", "mother": "wangguiyan", "son": "weizhen"}
my_family["grandfather"] = "weiguo"   #有对应key就修改,没有就添加

#删除字典中的项
del my_family ["son"]`
my_family.pop("father")
my_family.popitem()     #随机删除一项
print(my_family)

#查找
print(my_family.get("son"))  #无则打印none,有则打印对应值
print("mother" in my_family)  #打印True或False

#一些操作符
my_family.keys()         #返回所有key值
my_family.values()       #返回所有value值
my_family.setdefault("daughter", {"zhaolina"}) #先在字典中检索daughter,如果有就返回daughter对应的值,没有则创建新的key
my_family .items()   #将字典转换成列表
new_dict=dict.fromkeys([1,2,3],"waiting")  #初始化一个新的字典

#字典合并
me={}
my_school={"teacher": ["math", "physic", "PE"],
           "school": ["primary_school", "middle_school", "high_school", "college"],
           "location":["zunhua","zunhua","dalian","shenyang"]}
me.update(my_family)
me.update(my_school)
print(me)    #如果有相同的key值,后面的key值将会替换掉前面的key

#字典循环
for i in me:
    print(i, me[i])     #效率更高,直接索引调用

for k, v in me.items(): #先转换成列表
    print(k, v)

添加实例

>>> my_family= {"father": "weihaiqing", "mother": "wangguiyan", "son": "weizhen"}
>>> my_family["grandfather"] = "weiguo"
>>> print(my_family)
{'father': 'weihaiqing', 'mother': 'wangguiyan', 'son': 'weizhne', 'grandfather': 'weiguo'}

删除实例

>>> del my_family ["son"]
>>> my_family.pop("father")
'weihaiqing'
>>> my_family.popitem()
('daughter', {'zhaolina'})
>>> print(my_family)
{'mother': 'wangguiyan'}
>>> 

操作符实例

>>> my_family.keys()
dict_keys(['father', 'mother', 'son'])
>>> my_family.values()
dict_values(['weihaiqing', 'wangguiyan', 'weizhen'])
>>> my_family.setdefault("daughter", {"zhaolina"})
{'zhaolina'}
>>> my_family .items()
dict_items([('father', 'weihaiqing'), ('mother', 'wangguiyan'), ('son', 'weizhen'), ('daughter', {'zhaolina'})])

查找实例

>>> print(my_family.get("son"))
weizhen
>>> print("mother" in my_family)
True

 

合并实例

>>> me={}
>>> my_school={"teacher": ["math", "physic", "PE"],
           "school": ["primary_school", "middle_school", "high_school", "college"],
           "location":["zunhua","zunhua","dalian","shenyang"]}
>>> me.update(my_family)
>>> me.update(my_school)
>>> print(me)
{'father': 'weihaiqing', 'mother': 'wangguiyan', 'son': 'weizhen', 'grandfather': 'weiguo', 'teacher': ['math', 'physic', 'PE'], 'school': ['primary_school', 'middle_school', 'high_school', 'college'], 'location': ['zunhua', 'zunhua', 'dalian', 'shenyang']}
>>> 

之前一直用pycharm记录学习,每次修改尝试结果没有保存,忘记可以拿python shell直接演示,之后的笔记都以这次的形式记录。

 

posted on 2018-12-27 10:23  Wildwolf1995  阅读(135)  评论(0编辑  收藏  举报