導航:首頁 > 編程語言 > python動態創建字典

python動態創建字典

發布時間:2022-07-22 01:48:23

python 字典創建問題

python創建文件與文件夾1.文件的創建:一般創建.txt文件函數open(file,'mode')file為文件地址,若不存在則新建,若不再本目錄下,可以寫絕對路徑mode有以下幾種方式:r只讀 rb二進制只讀 w寫入且原有內容覆蓋 a在文件末尾追加打開後文件需要.close()關閉2.文件夾的創建:使用os.mkdir(ad)方式建立,ad為新建文件夾名稱的絕對路徑

Ⅱ Python中字典創建、遍歷、添加等實用操作技巧合集

欄位是Python是字典中唯一的鍵-值類型,是Python中非常重要的數據結構,因其用哈希的方式存儲數據,其復雜度為O(1),速度非常快。下面列出字典的常用的用途.
一、字典中常見方法列表
代碼如下:
#方法
#描述
-------------------------------------------------------------------------------------------------
D.clear()
#移除D中的所有項
D.()
#返回D的副本
D.fromkeys(seq[,val])
#返回從seq中獲得的鍵和被設置為val的值的字典。可做類方法調用
D.get(key[,default])
#如果D[key]存在,將其返回;否則返回給定的默認值None
D.has_key(key)
#檢查D是否有給定鍵key
D.items()
#返回表示D項的(鍵,值)對列表
D.iteritems()
#從D.items()返回的(鍵,值)對中返回一個可迭代的對象
D.iterkeys()
#從D的鍵中返回一個可迭代對象
D.itervalues()
#從D的值中返回一個可迭代對象
D.keys()
#返回D鍵的列表
D.pop(key[,d])
#移除並且返回對應給定鍵key或給定的默認值D的值
D.popitem()
#從D中移除任意一項,並將其作為(鍵,值)對返回
D.setdefault(key[,default])
#如果D[key]存在則將其返回;否則返回默認值None
D.update(other)
#將other中的每一項加入到D中。
D.values()
#返回D中值的列表
二、創建字典的五種方法
方法一:
常規方法
代碼如下:
#
如果事先能拼出整個字典,則此方法比較方便
>>>
D1
=
{'name':'Bob','age':40}
方法二:
動態創建

代碼如下:
#
如果需要動態地建立字典的一個欄位,則此方法比較方便
>>>
D2
=
{}
>>>
D2['name']
=
'Bob'
>>>
D2['age']
=
40
>>>
D2
{'age':
40,
'name':
'Bob'}
方法三:
dict--關鍵字形式
代碼如下:
#
代碼比較少,但鍵必須為字元串型。常用於函數賦值
>>>
D3
=
dict(name='Bob',age=45)
>>>
D3
{'age':
45,
'name':
'Bob'}
方法四:
dict--鍵值序列
代碼如下:
#
如果需要將鍵值逐步建成序列,則此方式比較有用,常與zip函數一起使用
>>>
D4
=
dict([('name','Bob'),('age',40)])
>>>
D4
{'age':
40,
'name':
'Bob'}

代碼如下:
>>>
D
=
dict(zip(('name','bob'),('age',40)))
>>>
D
{'bob':
40,
'name':
'age'}
方法五:
dict--fromkeys方法#
如果鍵的值都相同的話,用這種方式比較好,並可以用fromkeys來初始化

代碼如下:
>>>
D5
=
dict.fromkeys(['A','B'],0)
>>>
D5
{'A':
0,
'B':
0}
如果鍵的值沒提供的話,默認為None
代碼如下:
>>>
D3
=
dict.fromkeys(['A','B'])
>>>
D3
{'A':
None,
'B':
None}
三、字典中鍵值遍歷方法

代碼如下:
>>>
D
=
{'x':1,
'y':2,
'z':3}
#
方法一
>>>
for
key
in
D:
print
key,
'=>',
D[key]
y
=>
2
x
=>
1
z
=>
3
>>>
for
key,
value
in
D.items():
#
方法二
print
key,
'=>',
value
y
=>
2
x
=>
1
z
=>
3
>>>
for
key
in
D.iterkeys():
#
方法三
print
key,
'=>',
D[key]
y
=>
2
x
=>
1
z
=>
3
>>>
for
value
in
D.values():
#
方法四
print
value
2
1
3
>>>
for
key,
value
in
D.iteritems():
#
方法五
print
key,
'=>',
value
y
=>
2
x
=>
1
z
=>
3
Note:用D.iteritems(),
D.iterkeys()的方法要比沒有iter的快的多。
四、字典的常用用途之一代替switch
在C/C++/Java語言中,有個很方便的函數switch,比如:
代碼如下:
public
class
test
{
public
static
void
main(String[]
args)
{
String
s
=
"C";
switch
(s){
case
"A":
System.out.println("A");
break;
case
"B":
System.out.println("B");
break;
case
"C":
System.out.println("C");
break;
default:
System.out.println("D");
}
}
}
在Python中要實現同樣的功能,
方法一,就是用if,
else語句來實現,比如:

代碼如下:
from
__future__
import
division
def
add(x,
y):
return
x
+
y
def
sub(x,
y):
return
x
-
y
def
mul(x,
y):
return
x
*
y
def
div(x,
y):
return
x
/
y
def
operator(x,
y,
sep='+'):
if
sep
==
'+':
print
add(x,
y)
elif
sep
==
'-':
print
sub(x,
y)
elif
sep
==
'*':
print
mul(x,
y)
elif
sep
==
'/':
print
div(x,
y)
else:
print
'Something
Wrong'
print
__name__
if
__name__
==
'__main__':
x
=
int(raw_input("Enter
the
1st
number:
"))
y
=
int(raw_input("Enter
the
2nd
number:
"))
s
=
raw_input("Enter
operation
here(+
-
*
/):
")
operator(x,
y,
s)
方法二,用字典來巧妙實現同樣的switch的功能,比如:

代碼如下:
#coding=gbk
from
__future__
import
division
x
=
int(raw_input("Enter
the
1st
number:
"))
y
=
int(raw_input("Enter
the
2nd
number:
"))
def
operator(o):
dict_oper
=
{
'+':
lambda
x,
y:
x
+
y,
'-':
lambda
x,
y:
x
-
y,
'*':
lambda
x,
y:
x
*
y,
'/':
lambda
x,
y:
x
/
y}
return
dict_oper.get(o)(x,
y)
if
__name__
==
'__main__':
o
=
raw_input("Enter
operation
here(+
-
*
/):
")
print
operator(o)

Ⅲ 一個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
"
",
line
1,
in
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如何創建字典

zidian = {key:value,}
例如:
language = {'China':'chinese',
'Japan':'japanese',
}

Ⅳ python字典如何添加字典

python字典添加字典的方法:
1、首先建立一個新的字典
2、調用updata()函數,把新字典裡面的鍵值對更新到dict里
3、列印dict,字典添加成功。
結果如下

Ⅵ Python中創建字典的幾種方法總結

1.傳統的文字表達式:
>>>d={'name':'Allen','age':21,'gender':'male'}
>>>d
{'age':21,'name':'Allen','gender':'male'}
如果你可以事先拼出整個字典,這種方式是很方便的。
2.動態分配鍵值:
>>>d={}
>>>d['name']='Allen'
>>>d['age']=21
>>>d['gender']='male'
>>>d
{'age':21,'name':'Allen','gender':'male'}
如果你需要一次動態地建立一個字典的一個欄位,那麼這種方式比較合適。
字典與列表不同,不能通過偏移量進行復制,只能通過鍵來讀取或賦值,所以也可以這樣為字典賦值,當然訪問不存在的鍵會報錯:
>>>d[1]='abcd'
>>>d
{1:'abcd','age':21,'name':'Allen','gender':'male'}
>>>d[2]
Traceback(mostrecentcalllast):
File"<pyshell#9>",line1,in<mole>d[2]
KeyError:212345678
3.字典鍵值表
>>>c=dict(name='Allen',age=14,gender='male')
>>>c
{'gender':'male','name':'Allen','age':14}
因為這種形式語法簡單,不易出錯,所以非常流行。
這種形式所需的代碼比常量少,但是鍵必須都是字元串才行,所以下列代碼會報錯:
>>>c=dict(name='Allen',age=14,gender='male',1='abcd')
SyntaxError:keywordcan'tbeanexpression
4.字典鍵值元組表
>>>e=dict([('name','Allen'),('age',21),('gender','male')])
>>>e
{'age':21,'name':'Allen','gender':'male'}
如果你需要在程序運行時把鍵和值逐步建成序列,那麼這種方式比較有用。
5.所有鍵的值都相同或者賦予初始值:
>>>f=dict.fromkeys(['height','weight'],'normal')
>>>f
{'weight':'normal','height':'normal'}

Ⅶ 在python中健與值的數量不一樣如何創建字典

摘要 python---創建字典的方式

Ⅷ Python中如何動態往列表中添加字典

>>>keys=['a','b','c']
>>>values=[1,2,3]
>>>dictionary=dict(zip(keys,values))
>>>print(dictionary)
{'a':1,'b':2,'c':3}

Ⅸ 如何用python製作特定文章的字典

1、傳統的文字表達式:

123

>>> d={'name':'Allen','age':21,'gender':'male'}>>> d{'age': 21, 'name': 'Allen', 'gender': 'male'}

如果你可以事先拼出整個字典,這種方式是很方便的。
2、動態分配鍵值:

123456

>>> d={}>>> d['name']='Allen'>>> d['age']=21>>> d['gender']='male'>>> d{'age': 21, 'name': 'Allen', 'gender': 'male'}

如果你需要一次動態地建立一個字典的一個欄位,那麼這種方式比較合適。
字典與列表不同,不能通過偏移量進行復制,只能通過鍵來讀取或賦值,所以也可以這樣為字典賦值,當然訪問不存在的鍵會報錯:

12345678

>>> 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 <mole> d[2]KeyError: 2

3、字典鍵值表

123

>>> c = dict(name='Allen', age=14, gender='male')>>> c{'gender': 'male', 'name': 'Allen', 'age': 14}

因為這種形式語法簡單,不易出錯,所以非常流行。
這種形式所需的代碼比常量少,但是鍵必須都是字元串才行,所以下列代碼會報錯:

12

>>> c = dict(name='Allen', age=14, gender='male', 1='abcd')SyntaxError: keyword can't be an expression

4、字典鍵值元組表

123

>>> e=dict([('name','Allen'),('age',21),('gender','male')])>>> e{'age': 21, 'name': 'Allen', 'gender': 'male'}

如果你需要在程序運行時把鍵和值逐步建成序列,那麼這種方式比較有用。
5、所有鍵的值都相同或者賦予初始值:

123

>>> f=dict.fromkeys(['height','weight'],'normal')>>> f{'weight': 'normal', 'height': 'normal'}

以上這篇Python中創建字典的幾種方法總結(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

Ⅹ 用Python創建一個學生字典並可以查詢其中信息

你可以試試這個----------------------------------------------------------

# -*- coding:UTF-8 -*-


students=[]


def meun():

print("="*30)

print("*"*10+"學生信息管理"+"*"*10)

print("1.添加學生信息")

print("2.刪除學生信息")

print("3.指定學號查詢學生信息")

print("4.查詢全部學生信息")

print("5.保存信息")

print("0.退出系統")

print("="*30)



def add_new_info():

global students

print("您選擇了添加學生信息功能")

name = input("請輸入學生姓名:")

stuId = input("請輸入學生學號(學號不可重復):")

age = input("請輸入學生年齡:")

#驗證學號是否唯一

i = 0

leap = 0

for temp in students:

if temp['id'] == stuId:

leap = 1

break

else:

i = i + 1

if leap == 1:

print("輸入學生學號重復,添加失敗!")

break

else:

# 定義一個字典,存放單個學生信息

stuInfo = {}

stuInfo['name'] = name

stuInfo['id'] = stuId

stuInfo['age'] = age

# 單個學生信息放入列表

students.append(stuInfo)

print("添加成功!")



def del_info():

global students

print("您選擇了刪除學生功能")

delId=input("請輸入要刪除的學生學號:")

#i記錄要刪除的下標,leap為標志位,如果找到leap=1,否則為0

i = 0

leap = 0

for temp in students:

if temp['id'] == delId:

leap = 1

break

else:

i=i+1

if leap == 0:

print("沒有此學生學號,刪除失敗!")

else:

del students[i]

print("刪除成功!")



def search_info():

global students

searchID=input("請輸入你要查詢學生的學號:")

#驗證是否有此學號

i = 0

leap = 0

for temp in students:

if temp['id'] == searchID:

leap = 1

break

else:

i = i + 1

if leap == 0:

print("沒有此學生學號,查詢失敗!")

else:

print("找到此學生,信息如下:")

print("學號:%s 姓名:%s 年齡:%s "%(temp['id'],temp['name'],temp['age']))



def print_all_info():

print("序號 學號 姓名 年齡")

for temp in students:

print("sno:%s,stuName:%s,stuAge:%s" %(temp['id'],temp['name'],temp['age']))

print("*"*20)

def loda_data():

#加在之前存儲的數據

global students

f = open("info_data.data")

content = f.read()

info_list = eval(content)

f.close()


def main():

#加在數據(先存好數據,在打開這個數據直接讀取數據)

#load_data()

while True:

#1.列印工程

meun()

#2.獲取用戶的選擇

key = input("請輸入要進行的操作):")

#3.根據用戶的選擇,作出相應的事件

if key == "1":

add_new_info()

elif key == "2":

del_info()

elif key == "3":

search_info()

elif key == "4":

print_all_info()

elif key == "5":

save_data()

elif key == "0":

exit_flag = input("你確定要退出嗎?(yes or no)")

if exit_flag == "yes":

break

else:

print("輸入有誤,請重新輸入。。。")

input(" 按回車鍵可以繼續。。。")

continue

#程序開始

main()

摘自網頁鏈接-------------------------------------------------------------------

請採納,謝謝

閱讀全文

與python動態創建字典相關的資料

熱點內容
堵車如何緩解壓力 瀏覽:15
喜鵲快貸app怎麼了 瀏覽:263
海龜編輯器積木編程怎麼安裝 瀏覽:185
程序員理發店生意怎麼樣 瀏覽:603
程序員羅技 瀏覽:180
軟考初級程序員課程2021下載 瀏覽:491
杭州程序員奶奶 瀏覽:880
不聽命令造成錯誤 瀏覽:981
kool系統源碼 瀏覽:610
流氓app在哪裡看 瀏覽:98
域名購買了怎麼指向伺服器 瀏覽:121
安卓手機如何讓照片顏色反轉 瀏覽:859
怎麼下載卓睿安手機版 瀏覽:514
h3crange命令 瀏覽:468
php前景和python 瀏覽:338
php壓縮圖片內存大小 瀏覽:495
在哪裡可以查看雲伺服器的信息 瀏覽:70
python讀取非txt文件 瀏覽:799
艾莫迅用什麼編程軟體好 瀏覽:227
android文件存儲讀取 瀏覽:214