python学习之字典

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之字典相关的知识,希望对你有一定的参考价值。

1.字典

列表存储的数据比较单一也不够灵活,这时我们可以使用字典来存储某些多内容的数据

1.简单的字典
技术分享
book={
    huqiang:13457412571,
    Jasper:110110110111,
    despereado:784137611
}
View Code
输出结果:
{‘Jasper‘: 110110110111, ‘huqiang‘: 13457412571, ‘despereado‘: 784137611}
2.字典里嵌套字典

技术分享
book_list={
    430424199103057689:{#字典里再加字典
        name:"huqiang",#name是key,huqiang是value
        age:"23",
        addr:"hunan"
    },
    4304241991030571689: {
        name: "huqiang",
        age: "23",
        addr: "hunan"
    },
    430424198903057689: {
        name: "huqiang2",
        age: "231",
        addr: "hunan1"
    }
}
print(book_list)
#字典是key-value对应,自动去重,比列表存储信息更灵活
View Code
输出结果:

{430424199103057689: {‘age‘: ‘23‘, ‘name‘: ‘huqiang‘, ‘addr‘: ‘hunan‘}, 4304241991030571689: {‘age‘: ‘23‘, ‘name‘: ‘huqiang‘, ‘addr‘: ‘hunan‘}, 430424198903057689: {‘age‘: ‘231‘, ‘name‘: ‘huqiang2‘, ‘addr‘: ‘hunan1‘}}

 

3.取key对应的value值

print(book_list[430424199103057689])
输出结果:
{‘addr‘: ‘hunan‘, ‘age‘: ‘23‘, ‘name‘: ‘huqiang‘}

4.修改value值
book_list[430424199103057689][‘name‘]="abc"
print(book_list[430424199103057
)
输出结果:
{‘age‘: ‘23‘, ‘addr‘: ‘hunan‘, ‘name‘: ‘abc‘}
#提示:修改key值对应的value值,当key值不存在时会自动创建该值

book_list[430424199103057689][‘email‘]="40847394[email protected]"
print(book_list[430424199103057689])
输出结果:
{‘email‘: ‘[email protected]‘, ‘addr‘: ‘hunan‘, ‘name‘: ‘abc‘, ‘age‘: ‘23‘}
5.删除字典
del book_list[430424199103057689][‘age‘]   #key值后不指定删除名称则删除整个字典列
print(book_list[430424199103057689])
输出结果:
{‘name‘: ‘abc‘, ‘email‘: ‘[email protected]‘, ‘addr‘: ‘hunan‘}
6.获取字典key值
v=book_list.get(430424199103057689110) #这个key值不存在
print(v)
#Get获取值,存在 则显示,不存在则None
输出结果:
None

7.更新字典
定义一个新字典book_list2
book_list2={
430424199103057689: {
‘name‘: "111111111111", #name对应的值修改为111111111111,其它值保持不变,原字典结构必须保持,不然会全部修改为新的字典
‘age‘: "23",
‘addr‘: "hunan"
}
}
book_list.update(book_list2)
print(book_list[430424199103057689])
输出结果:
{‘addr‘: ‘hunan‘, ‘age‘: ‘23‘, ‘name‘: ‘111111111111‘}

8.输出Key和value值
print(book_list.keys())
#打印字典所有key
print(book_list.values())
#打印字典所有value
9.字典应用for循环
循环字典里的key值
for key in book_list:
print(key)
输出结果:

430424199103057689
4304241991030571689
430424198903057689

循环字典的value值
for key in book_list:
print(book_list[key])
输出结果:

{‘name‘: ‘111111111111‘, ‘addr‘: ‘hunan‘, ‘age‘: ‘23‘}
{‘name‘: ‘huqiang‘, ‘addr‘: ‘hunan‘, ‘age‘: ‘23‘}
{‘name‘: ‘huqiang2‘, ‘addr‘: ‘hunan1‘, ‘age‘: ‘231‘}

循环字典里的key对应的value值

for key in book_list:
print(key,book_list[key])
输出结果:

430424199103057689 {‘name‘: ‘111111111111‘, ‘age‘: ‘23‘, ‘addr‘: ‘hunan‘}
4304241991030571689 {‘name‘: ‘huqiang‘, ‘age‘: ‘23‘, ‘addr‘: ‘hunan‘}
430424198903057689 {‘name‘: ‘huqiang2‘, ‘age‘: ‘231‘, ‘addr‘: ‘hunan1‘}

 

 
























































以上是关于python学习之字典的主要内容,如果未能解决你的问题,请参考以下文章

python学习之字典

python学习之字典的操作

python3学习之字典

Python学习之字典

python学习之字典

python学习之数据类型—字典dict