python中dict獲取關(guān)鍵字與值的實(shí)現(xiàn)
更新時(shí)間:2022年05月09日 17:10:17 作者:perter_L
這篇文章主要介紹了python中dict獲取關(guān)鍵字與值的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
dict獲取關(guān)鍵字與值
values()
>>> d
{'p': 34, 'l': 54, 'b': 88}
>>> for value in d.values():
... ? ? print(value)
...
34
54
88items()
>>> for key,value in d.items(): ... ? ? print(key,value) ... p 34 l 54 b 88
字典dict(關(guān)鍵字對(duì)應(yīng)的值為list)
方法一
代碼
# method 1
pages = {}
page = []
for img_name in os.listdir(args.image_dir):
pre_str = img_name[:2]
#print(pre_str)
if pre_str not in pages.keys():
tmp_list = []
tmp_list.append(os.path.join(args.image_dir, img_name))
pages[pre_str] = tmp_list
else:
pages[pre_str].append(os.path.join(args.image_dir, img_name))
print(pages)
輸出

方法二
代碼
# method 2
from collections import defaultdict
pages = defaultdict(list)
for img_name in os.listdir(args.image_dir):
pre_str = img_name[:2]
#print(pre_str)
pages[pre_str].append(os.path.join(args.image_dir, img_name))
print(list(pages.items()))
print(pages)
輸出 print(list(pages.items()))的輸出

print(pages)的輸出

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
已安裝Pytorch卻提示no?moudle?named?'torch'(沒有名稱為torch
這篇文章主要給大家介紹了關(guān)于已安裝Pytorch卻提示no?moudle?named?'torch'(沒有名稱為torch的模塊)的相關(guān)資料,當(dāng)提示"No module named 'torch'"時(shí),可能是由于安裝的Pytorch版本與當(dāng)前環(huán)境不匹配導(dǎo)致的,需要的朋友可以參考下2023-11-11
Python實(shí)現(xiàn)計(jì)算函數(shù)或程序執(zhí)行時(shí)間
在Python程序的開發(fā)過程中,一些程序需要獲取函數(shù)或程序的開始時(shí)間、結(jié)束時(shí)間和時(shí)間間隔等內(nèi)容用來分析和處理內(nèi)容。本文就來聊聊具體實(shí)現(xiàn)方法2023-02-02
Python深入分析@property裝飾器的應(yīng)用
這篇文章主要介紹了Python @property裝飾器的用法,在Python中,可以通過@property裝飾器將一個(gè)方法轉(zhuǎn)換為屬性,從而實(shí)現(xiàn)用于計(jì)算的屬性,下面文章圍繞主題展開更多相關(guān)詳情,感興趣的小伙伴可以參考一下2022-07-07
Python將字符串常量轉(zhuǎn)化為變量方法總結(jié)
在本篇內(nèi)容里我們給大家整理了一篇關(guān)于Python將字符串常量轉(zhuǎn)化為變量方法的知識(shí)點(diǎn)總結(jié),有需要的朋友們學(xué)習(xí)下。2019-03-03
Python裝飾器原理與簡(jiǎn)單用法實(shí)例分析
這篇文章主要介紹了Python裝飾器原理與簡(jiǎn)單用法,結(jié)合實(shí)例形式分析了Python裝飾器的概念、原理、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下2018-04-04

