本文目錄一覽:
- 1、求助python大神,編寫程序,實現以下功能:(1)創建空字典
- 2、python創建字典有多少種方法
- 3、python 怎樣創建一個字典
- 4、python字典中如何創建字典
- 5、怎麼用PYTHON編輯字典程序 急求
求助python大神,編寫程序,實現以下功能:(1)創建空字典
# 創建 dic_student 字典
dic_student = dict()
# 依次輸入姓名和年齡,存入dic_student字典,共 5 組數據
for i in range(5):
name = input().strip()
age = int(input().strip())
dic_student.update({name: age})
# 按行輸出,中間用 \t 隔開
for key, value in dic_student.items():
print(key, value, sep=’\t’)
python創建字典有多少種方法
兩種
法一使用賦值符號直接創建字典
法二使用內置函數dict創建字典
python 怎樣創建一個字典
1.傳統的文字表達式:
d={‘name’:’Allen’,’age’:21,’gender’:’male’} d
{‘age’: 21, ‘name’: ‘Allen’, ‘gender’: ‘male’}123
如果你可以事先拼出整個字典,這種方式是很方便的。
2.動態分配鍵值:
d={} d[‘name’]=’Allen’ d[‘age’]=21 d[‘gender’]=’male’ d
{‘age’: 21, ‘name’: ‘Allen’, ‘gender’: ‘male’}123456
如果你需要一次動態地建立一個字典的一個欄位,那麼這種方式比較合適。
字典與列表不同,不能通過偏移量進行複製,只能通過鍵來讀取或賦值,所以也可以這樣為字典賦值,當然訪問不存在的鍵會報錯:
d[1]=’abcd’ d
{1: ‘abcd’, ‘age’: 21, ‘name’: ‘Allen’, ‘gender’: ‘male’} d[2]
Traceback (most recent call last):
File “pyshell#9”, line 1, in module
d[2]
KeyError: 212345678
3.字典鍵值表
c = dict(name=’Allen’, age=14, gender=’male’) c
{‘gender’: ‘male’, ‘name’: ‘Allen’, ‘age’: 14}123
因為這種形式語法簡單,不易出錯,所以非常流行。
這種形式所需的代碼比常量少,但是鍵必須都是字元串才行,所以下列代碼會報錯:
c = dict(name=’Allen’, age=14, gender=’male’, 1=’abcd’)SyntaxError: keyword can’t be an expression12
4.字典鍵值元組表
e=dict([(‘name’,’Allen’),(‘age’,21),(‘gender’,’male’)]) e
{‘age’: 21, ‘name’: ‘Allen’, ‘gender’: ‘male’}123
如果你需要在程序運行時把鍵和值逐步建成序列,那麼這種方式比較有用。
5.所有鍵的值都相同或者賦予初始值:
f=dict.fromkeys([‘height’,’weight’],’normal’) f
{‘weight’: ‘normal’, ‘height’: ‘normal’}
python字典中如何創建字典
python—創建字典的方式
1、用{}創建字典
代碼:
x = {“a”:”1″, “b”:”2″}
print x
輸出:
{‘a’: ‘1’, ‘b’: ‘2’}
2、用內置函數dict()
(1)、入參為類似a=”1″的鍵值對
代碼:
x = dict(a=”1″, b=”2″)
print x
輸出:
{‘a’: ‘1’, ‘b’: ‘2’}
(2)、入參為一個元組,元組內部是一系列包含兩個值的元組,例如((“a”, “1”), (“b”, “2”))
代碼:
x = dict(((“a”, “1”), (“b”, “2”)))
print x
輸出
{‘a’: ‘1’, ‘b’: ‘2’}
(3)、入參為一個元組,元組內部是一系列包含兩個值的列表,例如([“a”, “1”], [“b”, “2”])
代碼:
x = dict(([“a”, “1”], [“b”, “2”]))
print x
輸出:
{‘a’: ‘1’, ‘b’: ‘2’}
(4)、入參為一個列表,列表內部是一系列包含兩個值的元組,例如[(“a”, “1”),(“b”, “2”)]
代碼:
x = dict([(“a”, “1”),(“b”, “2”)])
print x
輸出:
{‘a’: ‘1’, ‘b’: ‘2’}
(5)、入參為一個列表,列表內部是一系列包含兩個值的列表,例如[[“a”, “1”],[“b”, “2”]]
代碼:
x = dict([[“a”, “1”],[“b”, “2”]])
print x
輸出:
{‘a’: ‘1’, ‘b’: ‘2’}
注意:
對於a=”1″的方式初始化字典,字典的key只能為字元串,並且字元串不用加引號
對於dict內置函數初始化當入參是一個元組時,例如1)、2),元組內部的兩元素元組或者列表至少為兩個,否則會出錯
3、用戶fromkeys方法創建字典
代碼:
dict.fromkeys((“a”, “b”), 1)
print x
輸出:
{‘a’: 1, ‘b’: 1}
入參可以的第一個參數是一個列表或者元組,裡邊的值為key,第二個參數是所有key的value值
怎麼用PYTHON編輯字典程序 急求
#/usr/bin/python
if __name__ == ‘__main__’:
#read your dict file in a variable
d = {‘a’:’a\’s meaning here’, ‘b’:’xx’}
while True:
w = raw_input(“please input the word: “);
if w not in d:
print “%s not found” % w
else:
print “%s: %s” % (w, d[w])
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/193238.html