※참고 : https://github.com/dabeaz/python-cookbook



[Problem]

  1. 딕션어리로 계산하기 (1.8 Calcuating with Dictionaries 13페이지)
  2. 딕션어리 subset 추출하기
  3. 보통 2개의 딕션어리가 무엇인지 이해하기 (1.9 Finding Commonalities in Two Dictionaries 15페이지)
  4. common key로 딕션어리 리스트 분류하기

[Source]

1. 딕션어리로 계산하기

prices = {

   'ACME': 45.23,

   'AAPL': 612.78,

   'IBM': 205.55,

   'HPQ': 37.20,

   'FB': 10.75

}


# Find min and max price

min_price = min(zip(prices.values(), prices.keys()))        #딕션어리명.keys() 함수는 리스트 출력

   #딕션어리명.values() 함수는 값 출력

max_price = max(zip(prices.values(), prices.keys()))       #zip(), min(), max()는 각각 합침, 최소값, 최대값 의미


print('min price:', min_price)

print('max price:', max_price)


print('sorted prices:')

prices_sorted = sorted(zip(prices.values(), prices.keys()))     #sorted() 오름차순으로 정렬하는 함수

for price, name in prices_sorted:

    print('    ', name, price)


2. 딕션어리 subset 추출하기



3. 보통 2개의 딕션어리가 무엇인지 이해하기

a = {

   'x' : 1,

   'y' : 2,

   'z' : 3

}


b = {

   'w' : 10,

   'x' : 11,

   'y' : 2

}


print('Common keys:', a.keys() & b.keys())

print('Keys in a not in b:', a.keys() - b.keys())

print('(key,value) pairs in common:', a.items() & b.items())


4. common key로 딕션어리 리스트 분류하기

rows = [

    {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},

    {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},

    {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},

    {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}

]


from operator import itemgetter


rows_by_fname = sorted(rows, key=itemgetter('fname'))

rows_by_uid = sorted(rows, key=itemgetter('uid'))


from pprint import pprint


print("Sorted by fname:")

pprint(rows_by_fname)


print("Sorted by uid:")

pprint(rows_by_uid)


rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))

print("Sorted by lname,fname:")

pprint(rows_by_lfname)


※ 참고 : 
  • heapq 모듈은 nlargest() 와 nsmallest() 함수를 가짐

import heapq


nums = [-1, 2, 3, 4, 5, 6, -4, 22, 30, 100]

print(heapq.nlargest(3, nums)) #nums 에서 가장 큰 3개 수 출력

print(heapq.nsmallest(3, nums)) #nums 에서 가장 작은 3개 수 출력



nums = [1,8,2,-4]

import heapq

heap = list(nums)

heapq.heapify(heap)  #heap[0]에 가장 작은 수 부터 배치

heap


  • sorted(items)[:N] 또는 sorted(items)[-N:] 명령어가 빠르고 유사함


'#Python Cookbook #D.Beazly, B.K. Jones' 카테고리의 다른 글

#dictionary 예제 분류  (0) 2018.10.19

+ Recent posts