Compare python dictionary setdefault () and get () method

dict.setdefault (key, default = None) -> has acquired key value, otherwise setting key: default, and return to default, default value Default None

dict.get (key, default = None) -> there is key to get the value, otherwise default. default The default value is None.

 

Examples: Each loop iteration message character string, calculates the number of each character occurring

import pprint

message = "It is a good day, is not it?I mean the weather is good today."

count1 = {}
for char in message:
    count1.setdefault(char, 0)
    count1[char] += 1

count2 = {}
for char in message:
    count2[char] = count2.get(char, 0) + 1

pprint.pprint(count1)
pprint.pprint(count2)

 

Extended:

defaultdict: the plant belongs to a function in the collections module for building an object dictionary, a receiving function (callable) object as a parameter. What type parameter returns, key corresponding to the value is what type.

example:

General writing:

data = [("p", 1), ("p", 2), ("p", 3),
        ("h", 1), ("h", 2), ("h", 3)]
result = {}
for (key, value) in data:
    if key not in result:
        result[key] = []
    result[key].append(value)

setdefault:

result = {}
data = [("p", 1), ("p", 2), ("p", 3),
        ("h", 1), ("h", 2), ("h", 3)]
for (key, value) in data:
    result.setdefault(key, []).append(value)

defaultdict:

from collections import defaultdict
result = defaultdict(list)
data = [("p", 1), ("p", 2), ("p", 3),
        ("h", 1), ("h", 2), ("h", 3)]
for (key, value) in data:
    result[key].append(value)

 

Guess you like

Origin www.cnblogs.com/caizhanjin/p/11311857.html