woneuy01 / python2

0 stars 0 forks source link

dict #2

Open woneuy01 opened 4 years ago

woneuy01 commented 4 years ago

It’s so common to iterate over the keys in a dictionary that you can omit the keys method call in the for loop — iterating over a dictionary implicitly iterates over its keys.

It’s so common to iterate over the keys in a dictionary that you can omit the keys method call in the for loop — iterating over a dictionary implicitly iterates over its keys.

================================================ Got key apples Got key bananas Got key oranges Got key pears

woneuy01 commented 4 years ago

inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}

print(list(inventory.values())) print(list(inventory.items()))

for k in inventory: print("Got",k,"that maps to",inventory[k])

============================

[430, 312, 525, 217] [('apples', 430), ('bananas', 312), ('oranges', 525), ('pears', 217)] Got apples that maps to 430 Got bananas that maps to 312 Got oranges that maps to 525 Got pears that maps to 217

woneuy01 commented 4 years ago

inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}

print(inventory.get("apples")) print(inventory.get("cherries"))

print(inventory.get("cherries",0)) 없으면 0으로 표시

===================================

430 None 0

woneuy01 commented 4 years ago
get key Returns the value associated with key; None otherwise
get key,alt Returns the value associated with key; alt otherwise

inventory.get("cherries") if there is no cherries it will give 'NONE'

inventory.get("cherries",0) if there is no cherries it will give 0

inventory["cherries"] will give error

woneuy01 commented 4 years ago

dict is mutable

opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} alias = opposites

print(alias is opposites)

alias['right'] = 'left' print(opposites['right'])

===============

True left

woneuy01 commented 4 years ago

As you can see from the is operator, alias and opposites refer to the same object. If you want to modify a dictionary and keep a copy of the original, use the dictionary copy method.

Since acopy is a copy of the dictionary, changes to it will not effect the original. acopy = opposites.copy() acopy['right'] = 'left' # does not change opposites

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

t_count = 0 #initialize the accumulator variable for c in txt: if c == 't': t_count = t_count + 1 #increment the counter print("t: " + str(t_count) + " occurrences")

==================================

t: 17584 occurrences

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

t_count = 0 #initialize the accumulator variable s_count = 0 # initialize the s counter accumulator as well for c in txt: if c == 't': t_count = t_count + 1 #increment the t counter elif c == 's': s_count = s_count + 1 print("t: " + str(t_count) + " occurrences") print("s: " + str(s_count) + " occurrences")

===============================

t: 17584 occurrences s: 11830 occurrences

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

x = {} # start with an empty dictionary x['t'] = 0 # initialize the t counter x['s'] = 0 # initialize the s counter for c in txt: if c == 't': x['t'] = x['t'] + 1 # increment the t counter elif c == 's': x['s'] = x['s'] + 1 # increment the s counter

print("t: " + str(x['t']) + " occurrences") print("s: " + str(x['s']) + " occurrences")

=============================

t: 17584 occurrences s: 11830 occurrences

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

x = {} # start with an empty dictionary for c in txt: if c not in x:

we have not seen this character before, so initialize a counter for it

    x[c] = 0

#whether we've seen it before or not, increment its counter
x[c] = x[c] + 1

print("t: " + str(x['t']) + " occurrences") print("s: " + str(x['s']) + " occurrences"

=====================================

t: 17584 occurrences s: 11830 occurrences

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

letter_counts = {} # start with an empty dictionary for c in txt: if c not in letter_counts:

we have not seen this character before, so initialize a counter for it

    letter_counts[c] = 0

### whether we've seen it before or not, increment its counter
letter_counts[c] = letter_counts[c] + 1

for c in letter_counts.keys(): print(c + ": " + str(letter_counts[c]) + " occurrences")

==========================================

t: 17584 occurrences s: 11830 occurrences T: 699 occurrences h: 12892 occurrences e: 25410 occurrences : 43507 occurrences P: 203 occurrences r: 12054 occurrences o: 15506 occurrences j: 214 occurrences c: 5121 occurrences G: 235 occurrences u: 5665 occurrences .......

woneuy01 commented 4 years ago

f = open('scarlet.txt', 'r') txt_lines = f.readlines()

now txt_lines is a list, where each item is one

line of text from the story

print(len(txt_lines)) print(txt_lines[70:85])

========================

5155 ['(Being a reprint from the reminiscences of JOHN H. WATSON, M.D., late\n', 'of the Army Medical Department.) [2]\n', '\n', '\n', '\n', '\n', 'CHAPTER I. MR. SHERLOCK HOLMES.\n', '\n', '\n', 'IN the year 1878 I took my degree of Doctor of Medicine of the\n', 'University of London, and proceeded to Netley to go through the course\n', 'prescribed for surgeons in the army. Having completed my studies there,\n', 'I was duly attached to the Fifth Northumberland Fusiliers as Assistant\n', 'Surgeon. The regiment was stationed in India at the time, and before\n', 'I could join it, the second Afghan war had broken out. On landing at\n']

woneuy01 commented 4 years ago

sentence = "The dog chased the rabbit into the forest but the rabbit was too quick." words=sentence.split()

word_counts={} for word in words: if word not in word_counts: word_counts[word]=0 word_counts[word]=word_counts[word]+1

print(word_counts)

==============================

{'The': 1, 'dog': 1, 'chased': 1, 'the': 3, 'rabbit': 2, 'into': 1, 'forest': 1, 'but': 1, 'was': 1, 'too': 1, 'quick.': 1}

woneuy01 commented 4 years ago

stri = "what can I do"

char_d={} for word in stri: if word not in char_d: char_d[word]=0 char_d[word]=char_d[word]+1

print(char_d)

======================

{'t': 1, 'h': 1, ' ': 3, 'o': 1, 'c': 1, 'n': 1, 'd': 1, 'I': 1, 'a': 2, 'w': 1}

woneuy01 commented 4 years ago

f = open('scarlet2.txt', 'r') txt = f.read()

now txt is one long string containing all the characters

x = {} # start with an empty dictionary for c in txt: if c not in x:

we have not seen this character before, so initialize a counter for it

    x[c] = 0

#whether we've seen it before or not, increment its counter
x[c] = x[c] + 1

letter_values = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f':4, 'g': 2, 'h':4, 'i':1, 'j':8, 'k':5, 'l':1, 'm':3, 'n':1, 'o':1, 'p':3, 'q':10, 'r':1, 's':1, 't':1, 'u':1, 'v':4, 'w':4, 'x':8, 'y':4, 'z':10}

tot = 0 for y in x: if y in letter_values: tot = tot + letter_values[y] * x[y]

print(tot)

===================================

337353

woneuy01 commented 4 years ago

travel = {"North America": 2, "Europe": 8, "South America": 3, "Asia": 4, "Africa":1, "Antarctica": 0, "Australia": 1} total=0 for tra in travel.values(): total=total+tra

print(total)

==================== 19

woneuy01 commented 4 years ago

d = {'a': 194, 'b': 54, 'c':34, 'd': 44, 'e': 312, 'full':31}

ks = d.keys() best_key_so_far = list(ks)[0] # Have to turn ks into a real list before using [] to select an item for k in ks: if d[k] > d[best_key_so_far]: best_key_so_far = k

print("key " + best_key_so_far + " has the highest value, " + str(d[best_key_so_far]))


key e has the highest value, 312

woneuy01 commented 4 years ago

placement = "Beaches are cool places to visit in spring however the Mackinaw Bridge is near. Most people visit Mackinaw later since the island is a cool place to explore."

dict={} for pla in placement: if pla not in dict: dict[pla]=0 dict[pla] +=1
print(dict)

min_value=dict.keys()[0]

for pl in dict: dict[pl]<dict[min_value] min_value=pl

========================

{'B': 2, 'e': 17, 'a': 12, 'c': 8, 'h': 4, 's': 10, ' ': 27, 'r': 7, 'o': 10, 'l': 8, 'p': 6, 't': 8, 'v': 3, 'i': 13, 'n': 7, 'g': 2, 'w': 3, 'M': 3, 'k': 2, 'd': 2, '.': 2, 'x': 1}

woneuy01 commented 4 years ago

product = "iphone and android phones"

dict={} for pro in product: if pro not in dict: dict[pro]=0 dict[pro] +=1

max_value=dict.keys()[0]

temporarily select first value as max

for value in dict: if dict[value]>dict[max_value]: max_value=value

print(max_value, dict[max_value])

====================

n 4