本文目錄一覽:
- 1、Python 字典(dic)操作
- 2、如何利用Python設計語言操作不同數據類型字典
- 3、Python中字典創建、遍歷、添加等實用操作技巧合集
- 4、Python中的dict怎麼用
- 5、python中字典的使用方法怎麼樣的?
- 6、如何利用Python語言對字典數據類型進行各種操作
Python 字典(dic)操作
具體函數有 set(),pop(),update(),items(),keys(),values(),get(),setdefault()
python 字典操作
假設字典為 dics = {0:’a’, 1:’b’, ‘c’:3}
二是使用dict本身提供的一個 get 方法,在Key不存在的時候,返回None:
print dics.get(‘a’)
print dics.get(‘Paul’)
None
dict.get(key,default=None) 兩個選項 一個 key 一個 default= None —-default可以是任何strings(字元)
2.從字典中取值,若找到則刪除;當鍵不存在時,顯示異常key error
[方法] dics.pop(‘key’)
3.給字典添加一個條目。如果不存在,就指定特定的值;若存在,就算了。
[方法] dic.setdefault(key, value)
4. update
a = {‘a’:1,’b’:2}
a.update({‘c’:3})
a
{‘a’: 1,’c’: 3,’b’: 2}
a.update({‘c’:4})
a
{‘a’: 1,’c’: 4,’b’: 2}
dict的作用是建立一組 key 和一組 value 的映射關係,dict的key是不能重複的。
有的時候,我們只想要 dict 的 key,不關心 key 對應的 value,目的就是保證這個集合的元素不會重複,這時,set就派上用場了。
如何利用Python設計語言操作不同數據類型字典
第一步,聲明一個字典tree,賦值name和sale鍵,並列印字典值
第二步,添加字典鍵值對,字典是由鍵值對來構成的,聲明一個字典hudi並賦值;再次利用該字典添加一個鍵值對,然後列印添加後的值
第三步,對添加的鍵值對進行修改鍵值,獲取age這個鍵,然後重新賦值,列印修改後的結果
第四步,列印hudi字典,利用del刪除字典color鍵值對,然後列印刪除後的結果
第五步,再次列印hudi字典,利用clear()方法刪除該字典所有的鍵值對
第六步,利用pop()方法對字典鍵值對進行刪除,會先列印出刪除的鍵值對!
Python中字典創建、遍歷、添加等實用操作技巧合集
欄位是Python是字典中唯一的鍵-值類型,是Python中非常重要的數據結構,因其用哈希的方式存儲數據,其複雜度為O(1),速度非常快。下面列出字典的常用的用途.
一、字典中常見方法列表
代碼如下:
#方法
#描述
————————————————————————————————-
D.clear()
#移除D中的所有項
D.copy()
#返回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:
key,
‘=’,
D[key]
y
=
2
x
=
1
z
=
3
for
key,
value
in
D.items():
#
方法二
key,
‘=’,
value
y
=
2
x
=
1
z
=
3
for
key
in
D.iterkeys():
#
方法三
key,
‘=’,
D[key]
y
=
2
x
=
1
z
=
3
for
value
in
D.values():
#
方法四
value
2
1
3
for
key,
value
in
D.iteritems():
#
方法五
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
==
‘+’:
add(x,
y)
elif
sep
==
‘-‘:
sub(x,
y)
elif
sep
==
‘*’:
mul(x,
y)
elif
sep
==
‘/’:
div(x,
y)
else:
‘Something
Wrong’
__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(+
–
*
/):
“)
operator(o)
Python中的dict怎麼用
#字典的添加、刪除、修改操作
dict = {“a” : “apple”, “b” : “banana”, “g” : “grape”, “o” : “orange”}
dict[“w”] = “watermelon”
del(dict[“a”])
dict[“g”] = “grapefruit”
print dict.pop(“b”)
print dict
dict.clear()
print dict
#字典的遍歷
dict = {“a” : “apple”, “b” : “banana”, “g” : “grape”, “o” : “orange”}
for k in dict:
print “dict[%s] =” % k,dict[k]
#字典items()的使用
dict = {“a” : “apple”, “b” : “banana”, “c” : “grape”, “d” : “orange”}
#每個元素是一個key和value組成的元組,以列表的方式輸出
print dict.items()
#調用items()實現字典的遍歷
dict = {“a” : “apple”, “b” : “banana”, “g” : “grape”, “o” : “orange”}
for (k, v) in dict.items():
print “dict[%s] =” % k, v
#調用iteritems()實現字典的遍歷
dict = {“a” : “apple”, “b” : “banana”, “c” : “grape”, “d” : “orange”}
print dict.iteritems()
for k, v in dict.iteritems():
print “dict[%s] =” % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
print “dict[%s] =” % k, v
#使用列表、字典作為字典的值
dict = {“a” : (“apple”,), “bo” : {“b” : “banana”, “o” : “orange”}, “g” : [“grape”,”grapefruit”]}
print dict[“a”]
print dict[“a”][0]
print dict[“bo”]
print dict[“bo”][“o”]
print dict[“g”]
print dict[“g”][1]
dict = {“a” : “apple”, “b” : “banana”, “c” : “grape”, “d” : “orange”}
#輸出key的列表
print dict.keys()
#輸出value的列表
print dict.values()
#每個元素是一個key和value組成的元組,以列表的方式輸出
print dict.items()
dict = {“a” : “apple”, “b” : “banana”, “c” : “grape”, “d” : “orange”}
it = dict.iteritems()
print it
#字典中元素的獲取方法
dict = {“a” : “apple”, “b” : “banana”, “c” : “grape”, “d” : “orange”}
print dict
print dict.get(“c”, “apple”)
print dict.get(“e”, “apple”)
#get()的等價語句
D = {“key1” : “value1”, “key2” : “value2”}
if “key1” in D:
print D[“key1”]
else:
print “None”
#字典的更新
dict = {“a” : “apple”, “b” : “banana”}
print dict
dict2 = {“c” : “grape”, “d” : “orange”}
dict.update(dict2)
print dict
#udpate()的等價語句
D = {“key1” : “value1”, “key2” : “value2”}
E = {“key3” : “value3”, “key4” : “value4”}
for k in E:
D[k] = E[k]
print D
#字典E中含有字典D中的key
D = {“key1” : “value1”, “key2” : “value2”}
E = {“key2” : “value3”, “key4” : “value4”}
for k in E:
D[k] = E[k]
print D
#設置默認值
dict = {}
dict.setdefault(“a”)
print dict
dict[“a”] = “apple”
dict.setdefault(“a”,”default”)
print dict
#調用sorted()排序
dict = {“a” : “apple”, “b” : “grape”, “c” : “orange”, “d” : “banana”}
print dict
#按照key排序
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序
print sorted(dict.items(), key=lambda d: d[1])
#字典的淺拷貝
dict = {“a” : “apple”, “b” : “grape”}
dict2 = {“c” : “orange”, “d” : “banana”}
dict2 = dict.copy()
print dict2
#字典的深拷貝
import copy
dict = {“a” : “apple”, “b” : {“g” : “grape”,”o” : “orange”}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2[“b”][“g”] = “orange”
print dict
dict3[“b”][“g”] = “orange”
print dict
python中字典的使用方法怎麼樣的?
字典理解如下
另一個非常有用的 Python 內建數據類型是 字典 (參見 Mapping Types — dict )。字典在某些語言中可能稱為 聯合內存 ( associative memories )或 聯合數組 ( associative arrays )。序列是以連續的整數為索引,與此不同的是,字典以 關鍵字 為索引,關鍵字可以是任意不可變類型,通常用字元串或數值。如果元組中只包含字元串和數字,它可以作為關鍵字,如果它直接或間接的包含了可變對象,就不能當作關鍵字。不能用列表做關鍵字,因為列表可以用索引、切割或者 append() 和 extend() 等方法改變。
理解字典的最佳方式是把它看作無序的鍵: 值對 (key:value 對)集合,鍵必須是互不相同的(在同一個字典之內)。一對大括弧創建一個空的字典: {} 。初始化列表時,在大括弧內放置一組逗號分隔的鍵:值對,這也是字典輸出的方式。
字典的主要操作是依據鍵來存儲和析取值。也可以用 del 來刪除鍵:值對(key:value)。如果你用一個已經存在的關鍵字存儲值,以前為該關鍵字分配的值就會被遺忘。試圖從一個不存在的鍵中取值會導致錯誤。
對一個字典執行 list(d.keys()) 將返回一個字典中所有關鍵字組成的無序列表(如果你想要排序,只需使用 sorted(d.keys()) )。[2] 使用 in 關鍵字(指Python語法)可以檢查字典中是否存在某個關鍵字(指字典)。
如何利用Python語言對字典數據類型進行各種操作
第一步,聲明一個字典tree,賦值name和sale鍵,並列印字典值
第二步,添加字典鍵值對,字典是由鍵值對來構成的,聲明一個字典hudi並賦值;再次利用該字典添加一個鍵值對,然後列印添加後的值
第三步,對添加的鍵值對進行修改鍵值,獲取age這個鍵,然後重新賦值,列印修改後的結果
第四步,列印hudi字典,利用del刪除字典color鍵值對,然後列印刪除後的結果
第五步,再次列印hudi字典,利用clear()方法刪除該字典所有的鍵值對
第六步,利用pop()方法對字典鍵值對進行刪除,會先列印出刪除的鍵值對!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245146.html