溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用python字典添加數(shù)據(jù)的示例

發(fā)布時間:2020-11-09 09:29:49 來源:億速云 閱讀:288 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關(guān)使用python字典添加數(shù)據(jù)的示例,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

首先新建一個python文件命名為py3_dict.py,在這個文件中進行字符串操作代碼編寫(如下為代碼,文后有顯示運行效果):

#dictionaries 是一個Key-Value對形式的集合
#定義一個字典
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
print(student)
print(student['name'])
print(student['course'])
#字典的key和value可定義為immutable data type
#例如:定義key為1
student = {1:'yale','age':25,'course':['數(shù)學','計算機']}
print(student[1])
#訪問一個不存在的key
#會出現(xiàn)異常
#KeyError: 'phone'
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
#print(student['phone'])
#有時候我們希望不存在的key
#可以返回None或者一個默認值
#用如下方式實現(xiàn):
print(student.get('phone'))#None
print(student.get('phone','未找到'))#返回默認值:未找到
#往dict字典中添加數(shù)據(jù)
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
student['phone']='010-55555555'
print(student.get('phone','未找到'))#010-55555555
#改變已存在的key對應(yīng)的值
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
student['name']='andy'
print(student)
#使用update() 改變字典中的多個值
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
student.update({'name':'andy','age':26,'phone':'12345678'})
print(student)
#刪除一個key
#使用del 關(guān)鍵字
del student['phone']
print(student)
#或者使用之前提到過的pop()方法
#刪除數(shù)據(jù)
age = student.pop('age')
print(age)#26
print(student)
#使用len()查看字典中一共有多少key
student = {'name':'yale','age':25,'course':['數(shù)學','計算機']}
print(len(student))#3
#查看所有的key
print(student.keys())#dict_keys(['name', 'age', 'course'])
#查看所有的value
print(student.values())#dict_values(['yale', 25, ['數(shù)學', '計算機']])
#查看所有的key和value
#得到一對一對的key-value
#dict_items([('name', 'yale'), ('age', 25), ('course', ['數(shù)學', '計算機'])])
print(student.items())
#循環(huán)字典
#像list的方式循環(huán),打印的是key值
#name
#age
#course
for key in student:
 print(key)
#所以我們用items()方法循環(huán)數(shù)據(jù):
for key,value in student.items():
 print(key,value)
#結(jié)果:
#name yale
#age 25
#course ['數(shù)學', '計算機']

以上代碼運行效果:

{'name': 'yale', 'age': 25, 'course': ['數(shù)學', '計算機']}
yale
['數(shù)學', '計算機']
yale
None
未找到
010-55555555
{'name': 'andy', 'age': 25, 'course': ['數(shù)學', '計算機']}
{'name': 'andy', 'age': 26, 'course': ['數(shù)學', '計算機'], 'phone': '12345678'}
{'name': 'andy', 'age': 26, 'course': ['數(shù)學', '計算機']}
26
{'name': 'andy', 'course': ['數(shù)學', '計算機']}
3
dict_keys(['name', 'age', 'course'])
dict_values(['yale', 25, ['數(shù)學', '計算機']])
dict_items([('name', 'yale'), ('age', 25), ('course', ['數(shù)學', '計算機'])])
name
age
course
name yale
age 25
course ['數(shù)學', '計算機']

關(guān)于使用python字典添加數(shù)據(jù)的示例就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI