字典的操作詳解

2021-08-20 12:23:58 字數 1915 閱讀 8464

from collections import ordereddict

from collections import namedtuple

class student:

def

__init__(self

,name,age):

self.name = name

self.age = age

'''dict -->

字典是無序的,你輸出的結果可能每次都不一樣

(指的是順序

)ordereddict -->

'''ages =

'''#

輸出(key,value)

for item in ages.items():

print(item)

('a', 20)

('e', 12)

('b', 5)

('c', 10)

('d', 8)

''''''#輸出

(key,value)

for k, v in ages.items():

print(k, v)

''''''#輸出

keyfor item in ages.keys(): #

等價於for item in ages:

預設是按照進行輸出

print(item)cb

eda

''''''#輸出

value

for item in ages.values():

print(item)512

1020

8'''

'''#

關於字典的操作

for k in ages:

ages[k] = ages[k]

print(ages)

'''#

注意以下兩種的區別

#ages[key] = [value1,value2]

每乙個key

對應乙個列表

for item in ages.keys():

ages[item] = [item]

print(ages)

#for item in ages.keys():

ages[item] = [item,none]

print(ages)

#ages =

for item in ages.keys():

ages[item] = [ages[item],none]

print(ages)

#對列表進行排序#因為

item

是輸出(key, value) p[1]

相當於取出

value

若value

有多個值,則按照順序排列

ages_sort = sorted(ages.items(),

key=lambda p:p[1],

reverse=true)

print(ages_sort)

ages =

ages_sort = sorted(ages.items(),

key=lambda p:p[1][0],

reverse=true)

ages_sort = sorted(ages.items(),

key=lambda p:p[1][1],

reverse=true)

print(ages_sort)

#有序輸出字典,操作也可以和上面一樣

od = ordereddict([('a'

, 1), ('b'

, 2), ('c'

, 3)])

print(od)

#ordereddict([('a', 1), ('b', 2), ('c', 3)])

python字典操作例項詳解

usr bin env python3 coding utf 8 import turtle 全域性變數 詞頻排列顯示個數 count 10 單詞頻率陣列 作為y軸資料 data 單詞陣列 作為x軸資料 words y軸顯示放大倍數 可以根據詞頻數量進行調節 yscale 6 x軸顯示放大倍數 可以...

字典的操作

字典的兩大特點 無序,鍵唯一 通過dict 建立字典 dic1 dict name szx hoppy 123 print dic1 dic1 print dic1 字典的操作 dic1 dic1 age 18 print dic1 dic1.setdefault age 34 鍵存在,不改動,返回...

python操作字典 Python 字典操作高階

學習了 python 基本的字典操作後,學習這些高階操作,讓寫出的 更加優雅簡潔和 pythonic 與字典值有關的計算 問題想對字典的值進行相關計算,例如找出字典裡對應值最大 最小 的項。解決方案一 假設要從字典 中找出值最小的項,可以這樣做 d min zip d.values d.keys 2...