1. 程式人生 > >Write Cool Programs Using Python Dictionary.

Write Cool Programs Using Python Dictionary.

In this Python dictionary tutorial, you will learn how to use dictionary methods to write some cool programs such as a phone book program.

Also, you will get the source code of all the programs in this tutorial.

Please note,

Let’s get to business now.

What is a dictionary in Python?

Python dictionary associates a collection of keys with data values.

Unlike list in Python, a dictionary organizes information by association, not position.

That’s to say that, the key-value pairs are arranged in no particular order.

The key-value pairs in a dictionary are separated by a comma.

A colon (:) separates a key and its associated value.

I would love to refer these key-value pairs as entries.

The key-value pairs or entries are enclosed in curly braces ({ }).

Python dictionary example

In a  new file editor window,  type the following code snippet and save it as Dictionary_example.py

Dictionary example Python
123456 my_profile={"name":"Godson","gender":"male","status":"single"}constants={"k":1.3805e-23,"h":6.625e-34,"c":2.998e08}student_info={"name":"Oscar","dept":"computer science","level":300}empty_dict={}print("My profile:",my_profile,"Engineering constants:",constants,sep="\n")print("Student detail:",student_info,"Empty dictionary:",empty_dict,sep="\n")

Running Dictionary_example.py you will get:

Python
1234567891011 >>>RESTART:C:\Users\RAPTUREC.GODSON\Documents\Python Dictionary\Dictionary_example.py My profile:{'name':'Godson','gender':'male','status':'single'}Engineering constants:{'k':1.3805e-23,'h':6.625e-34,'c':299800000.0}Student detail:{'name':'Oscar','dept':'computer science','level':300}Empty dictionary:{}>>>

Note the following:

  • The keys in a dictionary can be any immutable Python data type(tuple)
  • Python dictionary keys can be strings or integers.
  • The associated value can be any Python data type.

In a  new file editor window,  type the following code snippet and save it as Dictionary_example2.py

Dictionary_example2 Python
1234567 x1={('chemistry','physics'):'science_subjects',('french','literature'):'art_subjects'}x={'science_subjects':['chemistry','physics'],'art_subjects':['french','literature']}s={'fruits':('apple','banana','strawberry'),'drinks':('coke','pepsi','fanta')}num={6:'six',7:'seven',8:'eight'}print("subjects:",x,"My favorite fruits and drinks:",s,sep="\n")print("Numbers:",num)print(x1)

Running Dictionary_example2.py you will get:

Python
123456789 >>>RESTART:C:\Users\RAPTUREC.GODSON\Documents\Python Dictionary\Dictionary_example2.py subjects:{'science_subjects':['chemistry','physics'],'art_subjects':['french','literature']}My favorite fruits anddrinks:{'fruits':('apple','banana','strawberry'),'drinks':('coke','pepsi','fanta')}Numbers:{6:'six',7:'seven',8:'eight'}{('chemistry','physics'):'science_subjects',('french','literature'):'art_subjects'}>>>

Python will raise a TypeError error if your keys are in list form.

Take a look:

Python
123456 >>>x={['chemistry','physics']:'science_subjects',['french','literature']:'art_subjects'}Traceback(most recent call last):File"<pyshell#4>",line1,in<module>x={['chemistry','physics']:'science_subjects',['french','literature']:'art_subjects'}TypeError:unhashable type:'list'>>>

How to know the number of entries in a Python dictionary.

Python has a built-in function for this operation.

The len() can be used to know the number of entries in a Python dictionary.

Observe the following code snippet. You can type them in Python’s interactive shell.

Python
123456 >>>student_details={'name':'Oscar','dept':'computer science','level':300}>>>len(student_details)3>>>print("There are",len(student_details),"entries in student details")There are3entries instudent details>>>

Adding keys to an existing Python Dictionary

You add a new key/value pair to a dictionary by using the subscript operator [].

Here’s the format:

“The variable name of your dictionary”[“key ”]=”Value”

Remember, that is just a format.

You use quotes appropriately.

The next code snippet creates an empty dictionary and adds three new entries:

(Please type them in Python’s interactive shell.)

Python
1234567 >>>my_profile={}>>>my_profile["name"]="Godson">>>my_profile["gender"]="male">>>my_profile["status"]="single">>>my_profile{'name':'Godson','gender':'male','status':'single'}>>>

Can you do one for me following these instructions?

  • Create an empty dictionary and assign it to a variable.
  • Let that variable be student_info
  • Add the following entries (key-value pair).
  1. name-Oscar”
  2. dept-computer science
  3. level-300

Now use a print statement to print your dictionary.

If you had problem on the way, don’t worry,

You are in a process, all you need is practice.

Here’s is our program    student_details.py

Python
12345 student_info={}student_info["name"]="Oscar"student_info["dept"]="computer science"student_info["level"]=300print("Student details:",student_info)

Running student_details.py, we will have:

Python
1234 >>>RESTART:C:\Users\RAPTUREC.GODSON\Documents\Python Dictionary\student_details.pyStudent details:{'name':'Oscar','dept':'computer science','level':300}>>>

Replacing  the values of an existing Python dictionary

Now, we have a program containing the details of Oscar.

What if Oscar is now in 400 level?

What can we do?

We can change the value associated with a particular key in a dictionary by using a subscript operator [].

Let’s change Oscar’s level with the code snippet below:

(Please type them in Python’s interactive shell.)

Python
12345 >>>student_details={'name':'Oscar','dept':'computer science','level':300}>>>student_details["level"]=400>>>student_details{'name':'Oscar','dept':'computer science','level':400}>>>

Accessing the values of a Python Dictionary.

Imagine a program, with numerous entries (key/value pairs) and we need just one value associated with a key.

We can print the whole dictionary using the print statement but that will be more work for us to look for that particular entry we need.

To save us time we can use the subscript operator [] to have access to values in a dictionary.

Here’s   an illustration:

(Please type them in Python’s interactive shell.)

Python
12345678910111213 >>>student_details={'name':'Oscar','dept':'computer science','level':300}>>>student_details["name"]'Oscar'>>>print("student's name:",student_details["name"])student's name: Oscar>>> print("student'sdept:",student_details["dept"])student's dept: computer science>>> print("student's gender:",student_details["gender"])Traceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    print("student'sgender:",student_details["gender"])KeyError:'gender'>>>

Note: If a key is not in the dictionary, Python raises a  KeyError. You can observe that in the last print statement in the code snippet above.

Project 1:

Write a Python program to prompt the user to enter the position of a chemical element and output the element. Your program should cover the first 20 elements.

The first 20 elements are:

Hydrogen, Helium, Lithium, Beryllium, Boron, Carbon, Nitrogen, Oxygen, Fluorine, Neon, Sodium, Magnesium, Aluminum, Silicon, Phosphorus, Sulphur, Chlorine, Argon, Potassium,  Calcium.

Save the program as elements.py

elements.py
123456789101112 print("To quit, press Enter")elements={1:"Hydrogen",2:"Helium",3:"Lithium",4:"Beryllium",5:"Boron",6:"Carbon",7:"Nitrogen",8:"Oxygen",9:"Flourine",10:"Neon",11:"Sodium",12:"Magnesium",13:"Aluminum"

相關推薦

Write Cool Programs Using Python Dictionary.

In this Python dictionary tutorial, you will learn how to use dictionary methods to write some cool programs such as a phone book program. Also, you w

xlwings: Write Excel macro using python instead of VBA

python3 value and eal world! create sheet fine lan i want to write Excel macros to deal with the data, but i am not familiar with VBA lan

Note 1 for <Pratical Programming : An Introduction to Computer Science Using Python 3>

3.3 整數 dir 運算 aso mbo int edt log Book Imformation : <Pratical Programming : An Introduction to Computer Science Using Python 3> 2n

Note 2 for <Pratical Programming : An Introduction to Computer Science Using Python 3>

follow more bject eval 3.1 語法 val sin pau Book Imformation : <Pratical Programming : An Introduction to Computer Science Using Python

Python dictionary 字典

創建 rom while new 括號 出現 .com objects ans Python字典是另一種可變容器模型,且可存儲任意類型對象,如字符串、數字、元組等其他容器模型。 一、創建字典字典由鍵和對應值成對組成。字典也被稱作關聯數組或哈希表。基本語法如下: dic

Python學習筆記】Coursera課程《Using Python to Access Web Data》 密歇根大學 Charles Severance——Week6 JSON and the REST Architecture課堂筆記

學習 except for num string net none input 網上 Coursera課程《Using Python to Access Web Data》 密歇根大學 Week6 JSON and the REST Architecture 13.5 Ja

How to edit Vector attribute tables using Python/ArcPy?

Method 1: arcpy.UpdateCursor This should do it and is a little simpler than the examples in the online help for UpdateCursorwhich is ne

筆記 Data Processing Using Python 5(GUI和圖形化介面)

繼承:私有屬性和方法 預設情況下,python類的成員屬性和方法都是public。 提供“訪問控制符號”來限定成員函式的訪問。 雙下劃線--—_var屬性會被_classname_var替換,將防止父類與子類中的同名衝突。 單下劃線———在屬性名前使用一個

筆記 Data Processing Using Python 1(用Python玩轉資料第一章)

輸入語句: price=raw_input("String"); 109; price; #值為109,型別為‘str’ 109; price; #值為109,型別為‘str’ 註釋問題:#註釋; \ 續行符;''',(不用加續行符; 縮排問題:增加縮排表示語句的開始;

Dataset creation and cleaning: Web Scraping using Python

In my last article, I discussed about generating a dataset using the Application Programming Interface (API) and Python libraries. APIs allow us to draw ve

New! 10x more awesome ways to write JSON configuration using Jsonnet.

JSON format, intended initially to replace XML for data-interchange, is widely used today to provide public data using APIs and web services as well as to

Linear Regression using Python

Linear Regression using PythonLinear Regression is usually the first machine learning algorithm that every data scientist comes across. It is a simple mode

Image Stitching using Python

Detailed DescriptionFeature DetectionIn this step, we identify points of interest in the image using the Harris corner detection method. For each point in

Training alternative Dlib Shape Predictor models using Python

1. Understanding the Training OptionsThe training process of a model is governed by a set of parameters. These parameters affect the size, accuracy and spe

1.0 An Introduction to Web Scraping using Python

Web Scraping 101– 1.0 An Introduction to Web Scraping using PythonWeb Scraping or Data Mining is the process of automated gathering of data from the intern

A Guide to AWS Lambdas using Python triggered by an API call

A Guide to AWS Lambdas using Python, triggered by an API callLet’s pretend that this is a relevant imageServerless computing has been a topic of discussion

Hacking up a reporting pipeline using Python and Excel

Hacking up a reporting pipeline using Python and ExcelWhen I arrived at Online Drinks, the reporting process was manual, prone to errors and was taking ove

Using Python and Linear Programming to Optimize Fantasy Football Picks

Using Python and Linear Programming to Optimize Fantasy Football PicksI’m not a big sports fan but I always liked the numbers. That’s why I was interested

How to Build Exponential Smoothing Models Using Python: Simple Exponential Smoothing, Holt, and…

How to Build Exponential Smoothing Models Using Python: Simple Exponential Smoothing, Holt, and Holt-WintersHow many iPhone XS will be sold in first 12 mon

Create your chatbot using Python NLTK

Create your chatbot using Python NLTKIt is estimated that by 2020, chatbots will be handling 85 percent of customer-service interactions; they are already