Python🐍

python - dictionary

2020-09-02  本文已影响0人  Pingouin

Dictionary

总结

Dictionaries are unordered collections specified by curly braces: {}. r Each dictionary item is a key-value pair (specified with a colon).
Key must be immutable.
Example: { 'a':5, 6:[1,2], (3,4):'abc'}
Assignment: D[2] = 'xyz' creates entry 2:'xyz'
The get method returns the value or the specified default: my dict(value,
default)
Iterating through a dictionary D:

1. a story of two collections

list: a linear collection of values that stay in order

dictionary: a 'bag' of values, each with its own label

2. dictionary intro

purse = dict()
purse['money'] = 12
purse['candy'] = 3
purse['tissue'] = 75
print(purse)
print(purse['candy']) # 3
purse['candy'] = purse['candy'] + 2 # update
print(purse)

3. comparing lists and dictionaries

ddd = dict()
ddd['age'] = 23
ddd['course'] = 'a lot'
print(ddd)
ddd['age'] = 25
print(ddd)

4. dictionary literals(constents)

jjj = {'ke':1, 'xinlei':2233, 'xjc':111}
print(jjj)
ooo = {}
print(ooo)

5. most common name? count the frequency

# when we see a new name
counts = dict()
names = ['zhang','ke','could','pass','the','pass']
for name in names:
    if name not in counts:
        counts[name] = 1
    else:
        counts[name] += 1
print(counts)
x = counts.get('pass',0) # to see if the key exists
# 0 is a default if 'pass' is not a key

6. get method for dictionaries

counts = dict()
names = ['adaf','dafsf','asdf','wre']
for name in names:
    counts[name] = counts.get(name,0) + 1
print(counts)

7. counts the word in text

# one line of text
counts = dict()
print('enter a line of text:')
line = input('')
words = line.split()
print('words:',words)
for word in words:
    counts[word] = counts.get(word,0) + 1
print('counts', counts)
# definite loops and dictionaries
counts = {'a':1,'b':222,'c':12}
for key in counts:
    print(key,counts[key])

8. get the keys

# 查找key
jjj = {'adfa':1,'sf':33, 're':100}
print(list(jjj))
print(jjj.keys()) # ['adfa','sf','re']
print(jjj.values())# [1,33,100]
print(jjj.items())# [('adfa',1),('sf',33),('re',100)] 
# this is a tuple

9. two iteration variables

# loop through key and value
jjj = {'adfa':1,'sf':33, 're':100}
for aa,bb in jjj.items():
    print(aa,bb)

10. 读file中出现次数最多的词

# input the file name
name = input('file name:')
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)
上一篇 下一篇

猜你喜欢

热点阅读