Python3中dict.keys()和dict_values轉換成list類型及訪問操作

前期回顧

python collections模塊中的Counter、OrderedDict、namedtuple、ChainMap、deque


問題引入

在學習完python 中的 collections模塊後,我們會遇到如何訪問內部某一具體元素的問題,查找網上沒有相關博文,故解決此問題。


代碼解決

from collections import Counter
s = "aaabcccdeff"
temp = Counter(s)
print(temp)           # Counter({'a': 3, 'c': 3, 'f': 2, 'b': 1, 'd': 1, 'e': 1})
print(type(temp))     # <class 'collections.Counter'>

print(temp.items())   # dict_items([('a', 3), ('b', 1), ('c', 3), ('d', 1), ('e', 1), ('f', 2)])
print(temp.keys())    # dict_keys(['a', 'b', 'c', 'd', 'e', 'f'])
print(temp.values())  # dict_values([3, 1, 3, 1, 1, 2])

# dict.keys()轉換成list類型
print(list(temp.keys()))        # ['a', 'b', 'c', 'd', 'e', 'f']
# dict_values轉化爲list類型
print(list(temp.values())[:])   # [3, 1, 3, 1, 1, 2]

之後的訪問就很簡單了 :)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章