Applied practice of try/except and dictionary editing and retrieval in Python

Introduction

Thank you for browsing. Please forgive English grammar. Please kindly tell the experts if there is something you can do about it.

Overview

-Search for a key from the dictionary. -If the specified key is found, the value is output, and if it is not found, "The key was not found" is output. -When the above process is completed, select whether to continue, edit the dictionary, or end.

Completion example

name_age = {"tanaka":33,"satou":23,"suzuki":29}
def dict_info (dict_tbl,key):

    try:
        print(key,"'s",dict_tbl[key]," years old.")

    except LookupError:
        print("[Key is not found.]")

op = 0
while op !=1:
    if op == 0:
        key = input("[Enter a name of the target.]:")
        dict_info(name_age,key)
        print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op == 2:
        print("[Edit the dictionary]")
        addn = input("[EDIT][Enter a name of the target]:")
        adda = int(input("[EDIT][Enter a age of the target.]:"))
        name_age[addn] = adda
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op !=1 and op !=0 and op !=2:
        while op != 0 and op != 1 and op != 2:
            print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
            op = int(input("[Choose 0 or 1 or 2]:"))

Execution example

 [Enter a name of the target.]:niwa
 [Key is not found.]
 [Conitnue>0] 
  [End>1] 
  [Edit the dictionary>2]
 [Choose 0 or 1 or 2]:0
 [Enter a name of the target.]:tanaka
 tanaka 's 33  years old.
 [Conitnue>0] 
  [End>1] 
  [Edit the dictionary>2]
 [Choose 0 or 1 or 2]:2
 [Edit the dictionary]
 [EDIT][Enter a name of the target]:masato
 [EDIT][Enter a age of the target.]:19
 {'tanaka': 33, 'satou': 23, 'suzuki': 29, 'masato': 19}
 [Choose 0 or 1 or 2]:1

Creating a dictionary

The name of the person is entered in the key of the dictionary name_age, and the age is entered in the value.

name_age = {"tanaka":33,"satou":23,"suzuki":29}

Creating a function to retrieve the key from the dictionary

If the key is found by try, print it. If the key is not found with except, "Key is not found." Is displayed.


def dict_info (dict_tbl,key):

    try:
        print(key,"'s",dict_tbl[key]," years old.")

    except LookupError:
        print("[Key is not found.]")

Create a statement to continue

Specify the key with input. op will be used later in while.


key = input("[Enter a name of the target.]:")
        dict_info(name_age,key)
        print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
        op = int(input("[Choose 0 or 1 or 2]:"))

Create a statement to edit the dictionary

addn specifies the key (personal name) to add. adda specifies the value (age) to add.


print("[Edit the dictionary]")
        addn = input("[EDIT][Enter a name of the target]:")
        adda = int(input("[EDIT][Enter a age of the target.]:"))
        name_age[addn] = adda
        print(name_age)
        op = int(input("[Choose 0 or 1 or 2]:"))

Create a statement that lets you choose to continue, end, or edit the dictionary

Two sentences, one for continuing and one for editing the dictionary, are inserted as shown below. I don't want to use brake, which is a forced termination as much as possible, so when I enter 1 for termination, the while loop ends. In the last if, if the wrong option is selected, it loops with while until the correct option is selected.


while op !=1:
    if op == 0:
        key = input("[Enter a name of the target.]:")
        dict_info(name_age,key)
        print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op == 2:
        print("[Edit the dictionary]")
        addn = input("[EDIT][Enter a name of the target]:")
        adda = int(input("[EDIT][Enter a age of the target.]:"))
        name_age[addn] = adda
        print(name_age)
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op !=1 and op !=0 and op !=2:
        while op != 0 and op != 1 and op != 2:
            print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
            op = int(input("[Choose 0 or 1 or 2]:"))

Complete

Completed by combining all.


name_age = {"tanaka":33,"satou":23,"suzuki":29}
op = 0
def dict_info (dict_tbl,key):

    try:
        print(key,"'s",dict_tbl[key]," years old.")

    except LookupError:
        print("[Key is not found.]")

while op !=1:
    if op == 0:
        key = input("[Enter a name of the target.]:")
        dict_info(name_age,key)
        print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op == 2:
        print("[Edit the dictionary]")
        addn = input("[EDIT][Enter a name of the target]:")
        adda = int(input("[EDIT][Enter a age of the target.]:"))
        name_age[addn] = adda
        print(name_age)
        op = int(input("[Choose 0 or 1 or 2]:"))

    if op !=1 and op !=0 and op !=2:
        while op != 0 and op != 1 and op != 2:
            print("[Conitnue>0]","\n","[End>1]","\n","[Edit the dictionary>2]")
            op = int(input("[Choose 0 or 1 or 2]:"))

in conclusion

Before posting, I thought, "I think you can only add it while calling it a dictionary edit." I don't call myself from the beginning to the end, so I want to call myself in the future. English is cool, but it's annoying to see. I wrote it at the beginning, but since I'm a beginner, I think it's strange, but please forgive me.

I want to quit beginners soon.

Recommended Posts

Applied practice of try/except and dictionary editing and retrieval in Python
(Bad) practice of using this in Python
Project Euler # 1 "Multiples of 3 and 5" in Python
Practice applying functions and global variables in Python
Explanation of edit distance and implementation in Python
"Linear regression" and "Probabilistic version of linear regression" in Python "Bayesian linear regression"
Calculation of standard deviation and correlation coefficient in Python
Difference between Ruby and Python in terms of variables
[python] Calculation of months and years of difference in datetime
Overview of generalized linear models and implementation in Python
Sample of getting module name and class name in Python
Summary of date processing in Python (datetime and dateutil)
How to store Python function in Value of dictionary (dict) and call function according to Key
I compared the speed of the reference of the python in list and the reference of the dictionary comprehension made from the in list.
Create a dictionary in Python
[python] Summary of how to retrieve lists and dictionary elements
Equivalence of objects in Python
Reference order of class variables and instance variables in "self. Class variables" in Python
Summary of Hash (Dictionary) operation support for Ruby and Python
Comparison of how to use higher-order functions in Python 2 and 3
Stack and Queue in Python
Introducing Python in Practice (PiP)
Python: Create a dictionary from a list of keys and values
[Python] Strengths and weaknesses of DataFrame in terms of time required
Avoid KeyError in python dictionary
[Tips] Problems and solutions in the development of python + kivy
Unittest and CI in Python
Implementation of quicksort in Python
Source installation and installation of Python
Count the number of Thai and Arabic characters well in Python
How to check the memory size of a dictionary in Python
Practice of data analysis by Python and pandas (Tokyo COVID-19 data edition)
List of Linear Programming (LP) solvers and modelers available in Python
Verify the compression rate and time of PIXZ used in practice
Get the title and delivery date of Yahoo! News in Python
Environment construction of python and opencv
Pixel manipulation of images in Python
The story of Python and the story of NaN
Notes on Python and dictionary types
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Difference between == and is in python
Installation of SciPy and matplotlib (Python)
View photos in Python and html
Expansion by argument of python dictionary
Sorting algorithm and implementation in Python
Division of timedelta in Python 2.7 series
Manipulate files and folders in Python
MySQL-automatic escape of parameters in python
About dtypes in Python and Cython
Handling of JSON files in Python
Assignments and changes in Python objects
Implementation of life game in Python
Waveform display of audio in Python
Check and move directories in Python
This and that of python properties
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Function synthesis and application in Python
Basic grammar of Python3 system (dictionary)
Export and output files in Python