Methods of Dictionaries

damjaeng-i·2022년 8월 17일
0

2022 PY4E

목록 보기
16/18
post-thumbnail

Many Counters with a Dictionary

One common use of dictionaries is counting how often we “see” something

>>> ccc = dict()
>>> ccc['csev'] = 1
>>> ccc['cwen'] = 1
>>> print(ccc)
{'csev': 1, 'cwen': 1}
>>> ccc['cwen'] = ccc['cwen'] + 1
>>> print(ccc)
{'csev': 1, 'cwen': 2}

Dictionary Tracebacks

  • It is an error to reference a key which is not in the dictionary
  • We can use the in operator to see if a key is in the dictionary
>>> ccc = dict()
>>> print(ccc['csev'])
KeyError: 'csev'

When we see a new name

When we encounter a new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
	if name not in counts :
			counts[name] = 1
	else : 
			counts[name] = counts[name] + 1
print(counts) 

The get method for dictionaries

The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us

Default value if they does not exist (and no Traceback).

if name in counts:
		x = counts[name]
else :
		x = 0

x = counts.get(name, 0)

{'csev': 2, 'zqian': 1, 'cwen': 2}

Simplified counting with get()

We can use get() and provide a default value of zero when the key is not yet in the dictionary - and then just add one

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
		counts[name] = counts.get(name, 0) + 1
print(counts) 

Counting Pattern

The general pattern to count the words in a line of text is to split the line into words, then loop through the words and use a dictionary to track the count of each word independently.

counts = dict()
print('Enter a line of text: ')
line = input('')

words = line.split()

print('Words:', words)

print('Counting...')
for word in words:
		counts[word] = counts.get(word, 0) + 1
print('Counts', counts) 

Definite Loops and Dictionaries

Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a dictionary - actually it goes through all of the keys in the dictionary and looks up the values

You can get a list of keys, values, or items(both) from a dictionary

Bonus: Two Iteration Variables!

  • We loop through the key-value pairs in a dictionary using “two” iteration variables
  • Each iteration, the first variable is the key and the second variable is the corresponding value for the key
jjj = {'chuck' : 1, 'fred' : 42, 'jan' : 100}
for aaa.bbb in jjj.items() :
		print(aaa, bbb) 
name = input('Enter file:')
handle = open(name)

counts = dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word,0) + 1

bigcount = None
bigword = None
for word,count in counts.items():
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count

print(bigword, bigcount)

Summary

  • What is a collection?
  • Lists versus Dictionaries
  • Dictionary constants
  • The most common word
  • Using the get() method
  • Hashing, and lack of order
  • Writing dictionary loops
  • Sneak peek: tuples
  • Sorting dictionaries
profile
목표 : 부지런한 개발자

0개의 댓글