建立有序字典
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'print(dic)#输出:OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
clear(清空有序字典)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic.clear()print(dic)#输出:OrderedDict()
copy(拷貝)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'new_dic = dic.copy()print(new_dic)#输出:OrderedDict([('k1', 'v1'), ('k2', 'v2')])
fromkeys(指定一個列表,把列表中的值作為字典的key,產生一個字典)
import collections dic = collections.OrderedDict() name = ['tom','lucy','sam']print(dic.fromkeys(name))print(dic.fromkeys(name,20))#输出:OrderedDict([('tom', None), ('lucy', None), ('sam', None)])# OrderedDict([('tom', 20), ('lucy', 20), ('sam', 20)])
items(傳回由「鍵值對組成元素「的列表)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'print(dic.items())#输出:odict_items([('k1', 'v1'), ('k2', 'v2')])
keys(取得字典所有的key)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'print(dic.keys())# 输出:odict_keys(['k1', 'k2'])
move_to_end(指定一個key,把對應的key-value移到最後)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'dic.move_to_end('k1')print(dic)# 输出:OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
pop(取得指定key的value,並在字典中刪除)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'k = dic.pop('k2')print(k,dic)# 输出:v2 OrderedDict([('k1', 'v1'), ('k3', 'v3')])
popitem(依照後進先出原則,刪除最後加入的元素,返回key-value)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'print(dic.popitem(),dic)print(dic.popitem(),dic)# 输出:('k3', 'v3') OrderedDict([('k1', 'v1'), ('k2', 'v2')])# ('k2', 'v2') OrderedDict([('k1', 'v1')])
setdefault(取得指定key的value,如果key不存在,則建立)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'val = dic.setdefault('k5')print(val,dic)# 输出:None OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k5', None)])
values(取得字典所有的value,返回一個列表)
import collections dic = collections.OrderedDict() dic['k1'] = 'v1'dic['k2'] = 'v2'dic['k3'] = 'v3'print(dic.values())# 输出:odict_values(['v1', 'v2', 'v3'])
以上是python3 OrderedDict類別(有序字典)使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!