Task 03: dictionary, tuple, boolean type, read / write file

Posted by countrygyrl on Mon, 21 Feb 2022 09:02:11 +0100

preface

This article mainly introduces the related contents of dictionary, tuple, boolean type and read-write file.

1, Dictionary

Dictionary (also known as dict) is a data storage method similar to list. But unlike lists, which can only get data with numbers, dictionaries can get data with anything. You can think of a dictionary as a database that stores and organizes data.
Compare the functions of lists and dictionaries:
List:

Dictionaries:

We use strings (not numbers) to get what we want from the stuff dictionary. We can also use strings to add new things to the dictionary. Moreover, you can also do without strings. We can do this:

In this code, I use numbers, so you see, when I print a dictionary, I can use both numbers and strings as keys. I can use anything. Well, most things, but pretend you can use anything now.
Of course, if a dictionary can only contain things, it would be stupid. Here's how to delete things with the keyword 'del':

1. A dictionary example

Map state names with their abbreviations and state abbreviations with cities. Remember that "mapping" or "association" is the core idea of the dictionary.

# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
  }
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
 }
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

# print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])

# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])

# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
     print(f"{state} is abbreviated {abbrev}")

# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
    print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
    print(f"{state} state is abbreviated {abbrev}")
    print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')

if not state:
    print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")

! [insert picture description here]( https://img-blog.csdnimg.cn/046b95d4d47845acaf5917342a16783f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBATmV2ZXIgIGdpdmUgIHVw,size_10,color_FFFFFF,t_70,g_se,x_16#pic_center

Write a dictionary code corresponding to Chinese province and province abbreviation:

# create a mapping of state to abbreviation
states = {
'Beijing': 'Beijing',
'Tianjin': 'Jin',
'Shanghai': 'Shanghai',
  }
# create a basic set of states and some cities in them
cities = {
'Liao': 'Liaoning',
'black': 'Heilongjiang',
'Lu': 'Shandong'
 }
# add some more cities
cities['Beijing'] = 'Beijing'
cities['Shanghai'] = 'Shanghai'
cities['Jin'] = 'Tianjin'

# print out some cities
print('-' * 10)
print("Beijing State has: ", cities['Beijing'])
print("Shanghai State has: ", cities['Shanghai'])

# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
     print(f"{state} is abbreviated {abbrev}")

# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
    print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
    print(f"{state} state is abbreviated {abbrev}")
    print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')

if not state:
    print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")

2, Tuple

Tuples are another data type, similar to lists.
Tuples are identified by (). Internal elements are separated by commas. However, tuples cannot be assigned twice, which is equivalent to a read-only list.

The following tuples are not valid because tuples are not allowed to be updated. The list is allowed to be updated:

3, Boolean type

• and
• or
• not
• != (not equal to)
• = = (equal to)
• > = (greater than or equal to)
• < = (less than or equal to)
• True
• False


4, Read write file

Close - close the file, just like "file - > Save as" in the editor.
Read - read the contents of the file. You can assign the read result to a variable.
readline - reads only one line of the text file.
truncate - empty the file. Be careful when emptying.
write('stuff ') - write something to the file.
seek(0) - move the read / write position to the beginning of the file.

Use these commands to make a small editor:

from sys import argv

filename = "test.txt"

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename, 'w')

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file.")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it.")
target.close()

After class exercises and supplements 1 (Chapter 2-3)

1.1 data type related exercises

1.1.1 data type conversion

Understand the usage of int(), float(), str(), type(), etc.

To convert the string '520' to decimal, you can use float():

Understand the slicing operation of strings:

1.2 list operation

The list is a box into which you can put everything.


What should I do to get 'sing' from lis?

The elements of the list can be modified:


Change the last element of the list to 50:

The list has a very useful operation called list consolidation:

The purpose of ord() is to return the unicode encoding of the symbol.

1.3 tuple operation


Tuple elements cannot be modified.

1.4 dictionary operation


Dictionary elements can be changed.

1.5 Sets set

Sets are a methematical concept, they are a lot like dictionaries with keys but no corresponding values.
Similar to the concept of mathematics, it is similar to the key of a dictionary, but there is no corresponding value.
Sets are enclosed by curly braces, elements seperated by comma, '{','}'.
Use flower brackets.
Sets do not support indexing or slicing, and do not have inherent order.
Subscript application and slicing are not supported.

1.6 operations and Boolean operations

operatordescribeexample
=Simple assignment operatorc = a + b: assign the operation result of a + b to c
+=Additive assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
%=Modulo assignment operatorC% = a is equivalent to C = C% a
**=Power assignment operatorc **= a is equivalent to c = c ** a
//=Integer division assignment operatorc //= a is equivalent to c = c // a


Boolean and comparison operations:

Logical operator
and or not



Is and is not operators and = = and= Differences between:
Is is used to judge whether the reference objects of two variables are the same, and = = is used to judge whether the values of the reference variables are equal.





Null value comparison:

summary

This task mainly explains the basic operations of dictionary, tuple, boolean type, reading and writing files and some practical exercises.

Topics: Python