Introduction to the usage of setdefault in python3 (code)

不言
Release: 2018-09-13 16:44:56
Original
2853 people have browsed it

This article brings you an introduction to the usage of setdefault in python3 (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

When dictionary d[k] cannot find the correct key, Python will throw an exception. Is there an elegant way to avoid this situation? The answer is yes.

index0.py Gets the word frequency information from the index and writes it into the list -- without using dict.setdefault

#!/usr/bin/env python
# coding=utf-8
import sys, re

WORD_RE = re.compile(r'\w+')

index = {}
with open(sys.argv[1], encoding='utf-8') as fp:
    for line_no, line in enumerate(fp, 1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start()+1
            location = (line_no, column_no)
            occurrences = index.get(word, [])
            occurrences.append(location)
            index[word] = occurrences

for word in sorted(index, key=str.upper):
    print(word, index[word])
Copy after login

zen.txt

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Copy after login

Execute python3 index0.py zen.txt

a [(19, 48), (20, 53)]
Although [(11, 1), (16, 1), (18, 1)]
ambiguity [(14, 16)]
and [(15, 23)]
are [(21, 12)]
aren [(10, 15)]
at [(16, 38)]
bad [(19, 50)]
be [(15, 14), (16, 27), (20, 50)]
beats [(11, 23)]
Beautiful [(3, 1)]
better [(3, 14), (4, 13), (5, 11), (6, 12), (7, 9), (8, 11), (17, 8), (18, 25)]
break [(10, 40)]
by [(1, 20)]
cases [(10, 9)]
...
Copy after login

index.py uses dict.setdefault and only uses one line to solve the problem of obtaining and updating the occurrence list of words

#!/usr/bin/env python
# coding=utf-8
import sys, re

WORD_RE = re.compile(r'\w+')

index = {}
with open(sys.argv[1], encoding='utf-8') as fp:
    for line_no, line in enumerate(fp, 1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start()+1
            location = (line_no, column_no)
            index.setdefault(word, []).append(location)

for word in sorted(index, key=str.upper):
    print(word, index[word])
Copy after login

In other words:

my_dict.setdefault(key, []).append(new_value)
Copy after login

Equivalent Yu

if key not in my_dict:
    my_dict[key] = []
my_dict[key].append(new_value)
Copy after login

The two have the same effect, except that setdefault only needs to complete the entire operation once, while the latter requires two queries

Related recommendations:

Operation dictionary in Python The use of the setdefault() method

Introduction to the use of super() and __class__ in Python3

The above is the detailed content of Introduction to the usage of setdefault in python3 (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template