[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)

3.3 Tuple

Tuples, unlike lists, are immutable. Therefore, it is not possible to add, delete, or change elements after defining a tuple.

3.3.1 Creating tuples using ()

The tuple is defined by a comma that passes through the value. It is customary to enclose the entire value in () because using () does not cause an error.

#You can use tuples to assign multiple variables at once.
>>> marx_tuple = ("Groucho","Choico","Harpo")
>>> marx_tuple
('Groucho', 'Choico', 'Harpo')
>>> a,b,c=marx_tuple
>>> a
'Groucho'
>>> b
'Choico'
>>> c
'Harpo'

>>> password = "aaaa"
>>> icecream = "bbbb"
>>> password,icecream =icecream,password
>>> password
'bbbb'
>>> icecream
'aaaa'

#Variable function tuple()You can use to create tuples from others.
>>> marx_list=["Groucho","Choico", 'Haapo']
>>> tuple(marx_list)
('Groucho', 'Choico', 'Haapo')

3.3.2 Comparison of tuples and lists

Features of tuples --Tuples consume less space --Tuples can be used as dictionary keys --There is no risk of accidentally rewriting tuple elements --Named tuples can be used as a simple substitute for objects --Function arguments are passed as tuples.

3.4 Dictionary

Dictionaries are similar to lists but do not use offsets such as 0 or 1 when selecting elements because the order of the elements is not controlled. Instead, give each value a ** unique key **. The key can be any immutable type.

Created by 3.4.1 {}

To create a dictionary, separate key: value pairs with commas and enclose them in {}.


>>> empty_dict ={}
>>> empty_dict
{}
>>> bierce ={
... "day":"A period of twenty-four hours,mostly misspent",
... "positive":"Mistaken at the top of one's voice",
... "misfortune":"The kind of fortune tha never misses",
... }
>>> bierce
{'day': 'A period of twenty-four hours,mostly misspent', 'positive': "Mistaken at the top of one's voice", 'misfortune': 'The kind of fortune tha never misses'}

3.4.2 Conversion using dict ()

You can use the dict () function to convert a sequence of two values into a dictionary. The first element of the sequence is the key and the second element is the value.

#List of two-element tuples
>>> lol = [["a","b"],["c","d"],["e","f"]]
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = [("a","b"),("c","d"),("e","f")]

#Tuple of a two-element list
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = (["a","b"],["c","d"],["e","f"])
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}

#List of two-letter strings
>>> los = ["ab","cd","ef"]
>>> dict(los)
{'a': 'b', 'c': 'd', 'e': 'f'}

#Two-letter string tuple
>>> los = ("ab","cd","ef")
>>> dict(los)
{'a': 'b', 'c': 'd', 'e': 'f'}


3.4.3 Addition or modification of elements by [key]

Use the key to refer to the element and assign the value. If the key already exists in the dictionary, the existing value will be replaced with the new value. ** If the key does not already exist, it will be added to the dictionary along with the value. ** **


#The key does not exist and is added to the dictionary as a set of keys and values
#Replace the value because the key already exists
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael'}
>>> pythons["Gilliam"] = "Gerry"
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael', 'Gilliam': 'Gerry'}


#If multiple keys are used, the last value remains.
>>> pythons["Gilliam"] = "Terry"
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael', 'Gilliam': 'Terry'}

#"Chapman"To the key"Graham"After substituting"Tatuo"Is replaced with.
>>> some_pythons = {
... "Chapman":"Graham",
... "Takada":"Takashi",
... "Palin":"Michael",
... "Chapman":"Tatuo",
... }
>>> some_pythons
{'Chapman': 'Tatuo', 'Takada': 'Takashi', 'Palin': 'Michael'}

3.4.4 Combine dictionaries with update ()

You can use the update () function to copy a dictionary key and value to another dictionary.

>>> pythons = {
... "Chapman":"Graham",
... "Takada":"Takashi",
... "Palin":"Michael",
... "Atushi":"Kataoka",
... }
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka'}

#If the second dictionary has the same keys contained in the first dictionary, the values in the second dictionary remain.
>>> others = {"Marx":"Gerge",'Takada': 'Takakakakakkakka'}
>>> pythons.update(others)
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takakakakakkakka', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}

3.4.5 Del deletes element with specified key


>>> del pythons["Marx"]
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takakakakakkakka', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Howard': 'Moe'}

3.4.6 Deleting all elements with clear ()

To remove all keys and values from the dictionary, use clear () or substitute an empty dictionary {} for the dictionary name.

>>> pythons.clear()
>>> pythons
{}

>>> pythons = {}
>>> pythons
{}

Using 3.4.7 in Key test


>>> pythons = {'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}

#"key" in "Dictionary name"Grammar
>>> "Chapman" in pythons 
True
>>> "Chaaaaan" in pythons
False

3.4.8 Getting elements with [key]

Specify the dictionary and key to retrieve the corresponding value.

>>> pythons = {'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}
>>> pythons["Howard"]
'Moe'

#Exception occurs if the key is not in the dictionary
>>> pythons["Howaaa"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Howaaa'

#3 ways to check if the key exists in advance to avoid exceptions

#use in
>>> "Howaaa" in pythons
False  

#Get for dictionary only()Use functions Pass dictionaries, keys, option values
#Returns the value of the key, if any
>>> pythons.get("Marx")
'Gerge'

#If there is no key, the specified option value is returned.(Second argument)
>>> pythons.get("Howaaa","Not a Python")
'Not a Python'

#If you don't make an option, it will be None
>>> pythons.get("Howaaa")

3.4.9 Get all keys with keys ()

You can get all the keys in the dictionary using keys (). In Python3, you also need to use the list () function when you want the return values of values () and items () to be regular Python lists.

>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
#Get all the keys in the dictionary
>>> signals.keys()
dict_keys(['green', 'yellow', 'red'])

3.4.10 Get all values with values ()


#To get all the values in the dictionary values()use
>>> list(signals.values())
['go', 'go faster', 'smile for the camera']

3.4.11 Get all key / value pairs with items ()


#All keys from the dictionary/If you want to retrieve value pairs, items()Use a function
>>> list(signals.items())
[('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')]

3.4.12 = Substitution and copy ()

As with lists, making changes to a dictionary affects all names that reference that dictionary.


#save_Affected because signals also refer to the same object
>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
>>> save_signals = signals
>>> signals["blue"]="confuse everyone"
>>> save_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}

#Key to another dictionary/If you want to copy the value copy()use.
>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
>>> original_signals = signals.copy()
>>> signals["blue"]="confuse everyone"
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
#Unaffected
>>> original_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}

3.5 set

A set is like a dictionary that throws out values and leaves only the keys. Use a dictionary if you want to add a value to a key.

3.5.1 Created by set ()

To create a set, use the set () function, or enclose one or more comma-separated values in {} and assign them.

#An empty set is a set with no elements
>>> empty_set = set()
>>> empty_set
set()

>>> even_numbers = {0,2,4,6,8}
>>> even_numbers
{0, 2, 4, 6, 8}

3.5.2 Conversion from other data types to sets by set ()

You can create a set by removing duplicate values from lists, strings, tuples, and dictionaries.


#"t","e"Are duplicated, but the set contains only one.
>>> set("letters")
{'l', 's', 't', 'r', 'e'}

#Create a set from a list
>>> set(["Danger","Dancer","Prancer","Mason-Dixon"])
{'Mason-Dixon', 'Danger', 'Prancer', 'Dancer'}

#Create a set from tuples
>>> set(("Ummaguma","Echoes","Atom Heart Mother"))
{'Echoes', 'Ummaguma', 'Atom Heart Mother'}

#set()If you pass the dictionary to, only the key will be used.
>>> set({'apple':"red", 'orange':"orange", 'cherry':"red"})
{'apple', 'orange', 'cherry'}

Test for the presence or absence of values using 3.5.3 in


#Both sets and dictionaries{}Although it is surrounded by, the set is just a sequence, while the dictionary is key:It is a sequence of value pairs.
>>> drinks = {
... "martini":{"vodka","vermouth"},
... "black russian":{"vodka","kahlua"},
... "manhattan":{"cream","kahlua","vodka"},
... "white russian":{"rye","vermouth","bitters"},
... "screwdriver":{"orange juice","vodka"}
... }

#Key from the dictionary drinks/Take out the pair of value in order, each name/Assign to contents and to contents"vodka"The value of the key including is output.
>>> for name,contents in drinks.items():
...  if "vodka" in contents:
...   print(name)
... 
martini
black russian
manhattan
screwdriver

#Key from the dictionary drinks/Take out the pair of value in order, each name/Assign to contents and to contents"vodka"Including"vermouth"Or"cream"The value of the key that does not include is output.
>>> for name,contents in drinks.items():
...  if "vodka" in contents and not ("vermouth" in contents or
...     "cream" in contents):
...      print(name)
... 
black russian
screwdriver

3.5.4 Calculate combinations

The result of the & operator is a set that contains all the elements contained in both sets.


#to contents"vermouth"、"orange juice"If both are not included&The operator is the empty set{}return it.
>>> for name,contents in drinks.items():
...  if contents & {"vermouth","orange juice"}:
...   print(name)
... 
martini
white russian
screwdriver


#3.5.3 Code rewriting at the bottom
>>> for name,contents in drinks.items():
...     if "vodka" in contents and not contents & {"vermouth","cream"}:
...         print(name)
... 
black russian
screwdriver

#Let's look at all set operators

>>> bruss = drinks["black russian"]
>>> wruss = drinks["white russian"]
>>> a={1,2}
>>> b={2,3}

#Intersection:&Or intersection()Use a function
>>> a & b
{2}
>>> a.intersection(b)
{2}
>>> bruss & wruss
set()

#Union:|Or union()Use a function
>>> a | b
{1, 2, 3}
>>> a.union(b)
{1, 2, 3}
>>> bruss | wruss
{'cream', 'kahlua', 'vodka'}

#Difference set:-Or difference()Use a function.(A set of elements that are included in the first set but not in the second set)
>>> a-b
{1}
>>> a.difference(b)
{1}
>>> bruss-wruss
set()
>>> wruss-bruss
{'cream'}

#Exclusive OR:^Or symmetric_difference()Use a function (elements contained in either)
>>> a ^ b
{1, 3}
>>> a.symmetric_difference(b)
{1, 3}
>>> bruss^wruss
{'cream'}

#Subset:<=Or issubset()use.
>>> a <=b
False
>>> a.issubset(b)
False
>>> bruss<=wruss
True
#Every set is a subset of itself.
>>> a<=a
True
>>> a.issubset(a)
True

#Whether the first set is a true subset of the second set.
#The second set must have another element in addition to all the elements of the first set.<Can be calculated with.
>>> a < b
False
>>> a<a
False
>>> bruss<wruss
True

#Superset: A relationship in which all elements of the second set are also elements of the first set, which is the opposite of the subset.
# >=Or is superset()Check with a function.
>>> a>=b
False
>>> a.issubset(b)
False
>>> wruss >= bruss
True
#All sets are supersets of themselves.
>>> a>=a
True
>>> a.issuperset(a)
True

#True superset: Whether the first set contains all the elements of the second set and other elements
>>> a > b
False
>>> wruss > bruss
True
#The set is not a direct superset of itself
>>> a>a
False

3.6 Data structure comparison

--The list is in square brackets [] --Tuples are commas --Dictionaries and sets are {}

Represented by

The reference method is as follows. --For lists and tuples, the numbers in the brackets are offset --For dictionaries, the key


>>> marx_list=["akagi","Takasuka","Syuda"]
>>> marx_tuple="akagi","Takasuka","Syuda"
>>> marx_dict={"akagi","Takasuka","Syuda"}
>>> marx_list=[2]
>>> marx_list=["akagi","Takasuka","Syuda"]
>>> marx_list[2]
'Syuda'
>>> marx_tuple[2]
'Syuda'
>>> marx_dict={"akagi":"banjo","Takasuka":"help","Syuda":"harp"}
>>> marx_dict["Syuda"]
'harp'

3.7 Larger data structure


>>> marxs=["akagi","Takasuka","Syuda"]
>>> pythons=["Gilliam","Cleese","Gilliam"] 
>>> stooges=["Moe","Curly","Larry"]

#Create tuples from individual lists
>>> tuple_of_lists=marxs,pythons,stooges
>>> tuple_of_lists
(['akagi', 'Takasuka', 'Syuda'], ['Gilliam', 'Cleese', 'Gilliam'], ['Moe', 'Curly', 'Larry'])

#Create a list including a list
>>> list_of_lists=[marxs,pythons,stooges]
>>> list_of_lists
[['akagi', 'Takasuka', 'Syuda'], ['Gilliam', 'Cleese', 'Gilliam'], ['Moe', 'Curly', 'Larry']]

#Create a dictionary of lists
#Since dictionary keys must be immutable, lists, dictionaries, and sets cannot be keys for other dictionaries.
>>> dict_of_lists ={"Marxes":marxes,"Pythons":pythons,"Stooges":stooges}
>>> dict_of_lists
{'Marxes': ['Groucho', 'Choico', 'Haapo'], 'Pythons': ['Gilliam', 'Cleese', 'Gilliam'], 'Stooges': ['Moe', 'Curly', 'Larry']}

#Lists, dictionaries, and sets cannot be keys to other dictionaries because dictionary keys must be immutable, but tuples can be keys.
>>> houses={
... (44.79,-43.55,373):"My House"}

Review assignment

Exercise 3-1 Make a list called years_list by arranging each year from the year of birth to the 5th birthday in order.

>>> years_list=[1994,1995,1996,1997,1998,1999]

Exercise 3-2 Which year did you reach your 3rd birthday in the elements of years_list?


#Note that the offset starts at 0
>>> years_list[4]
1998

Exercise 3-3 Which of the years was the oldest on the years_list?


#offset-The right end can be selected by specifying as 1.
>>> years_list[-1]
1999

Exercise 3-4 Let's make a list called things with the three strings "mozzarella", "cinderella", and "salmonella" as elements.

>>> things=["mozzarella","cinderella","salmonella"]
>>> things
['mozzarella', 'cinderella', 'salmonella']

Exercise 3-5 Capitalize the first letter of the string that refers to a human in the elements of things and display it in a list.

#capitalize()Uppercase the first character of the string in the function.
>>> things[1]=things[1].capitalize()
>>> things
['mozzarella', 'Cinderella', 'salmonella']

Exercise 3-6 Capitalize all illness elements in things.

#upper()Capitalize the element string in the function.
>>> things[2]=things[2].upper()
>>> things
['mozzarella', 'Cinderella', 'SALMONELLA']

Exercise 3-7 Remove and display illness elements.


#You can delete an element with del
>>> del things[2]
>>> things
['mozzarella', 'Cinderella']

Exercise 3-8 Create a list called surprise with "Groucho", "Chico", and "Harpo" as elements.

>>> surprize=["Groucho","Chico","Harpo"]
>>> surprize
['Groucho', 'Chico', 'Harpo']

Exercise 3-9 surprise Let's lowercase the last element of the list, reverse it, and then change the first letter back to uppercase.

#Make the last string all lowercase.
>>> surprize[2]=surprize[2].lower()

#Substitute the last element in reverse order
>>> surprize[2]=surprize[-1][::-1]

#Uppercase the first letter of the last element.
>>> surprize[2]=surprize[2].capitalize()
>>> surprize[2]
'Oprah'

Exercise 3-10 Create an English-French dictionary called e2f and display it.

>>> e2f={"dog":"chien","cat":"chat","walrus":"morse"}
>>> e2f
{'dog': 'chien', 'cat': 'chat', 'walrus': 'morse'}

Exercise 3-11 Use e2f to display French for the word walrus.

#Is the key"walrus"To display the value
>>> e2f["walrus"]
'morse'

Exercise 3-12 Let's make a French-English dictionary called f2e from e2f. Use items ().


#Don't forget to initialize f2e
>>> f2e={}

#items()Use to english each key and value,Store in french
>>> for english,french in e2f.items():
...  f2e[french] = english
... 
>>> f2e
{'chien': 'dog', 'chat': 'cat', 'morse': 'walrus'}

Exercise 3-13 Use f2e to display English for French chien.


#Is the key"chien"To display the value
>>> f2e["chien"]
'dog'

Exercise 3-14 Create and display a set of English words from the e2f key.


#Set creation is set()To use.
>>> set(e2f.keys())
{'walrus', 'dog', 'cat'}

Exercise 3-15 Let's make a multi-level dictionary called life. Use the strings "animals", "other", "plants" as the top-level key. The animals key should refer to other dictionaries with the keys "cats", "octpi", "emus". The "cats" key should refer to the list of strings "Henry", "Grumpy", "Lucy". All other keys should refer to an empty dictionary.


>>> life={"animals":{"cats":["Henry","Grumpy","Lucy"],"octpi":{},"emus":{}},"plants":{},"other":{}}

Exercise 3-16 Show the top key of life.


#key()Is used to display the key of the multiple dictionary life
>>> print(life.keys())
dict_keys(['animals', 'plants', 'other'])

Exercise 3-17 Show the keys for life ["animals"].


#key()Using multiple dictionaries life["animals"]Is displaying the key of
>>> print(life["animals"].keys())
dict_keys(['cats', 'octpi', 'emus'])

Exercise 3-18 Display the values for life ["animals"] ["cats"].


#Multiple dictionary life["animals"]["cats"]Is displaying the value of
>>> print(life["animals"]["cats"])
['Henry', 'Grumpy', 'Lucy']

Impressions

Until now, the comment was written next to the execution statement, but when I looked back, it turned out to be very difficult to see. It's easier to see by writing it above the execution statement, so let's fix the previous one.

References

"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"

Recommended Posts

[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)
[Introduction to Python3 Day 5] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.1-3.2.6)
[Introduction to Python3 Day 6] Chapter 3 Py tool lists, tuples, dictionaries, sets (3.2.7-3.2.19)
[Introduction to Python3 Day 8] Chapter 4 Py Skin: Code Structure (4.1-4.13)
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Introduction to Python3 Day 3] Chapter 2 Py components: Numbers, strings, variables (2.2-2.3.6)
[Introduction to Python3 Day 2] Chapter 2 Py Components: Numbers, Strings, Variables (2.1)
[Introduction to Python3 Day 4] Chapter 2 Py Components: Numbers, Strings, Variables (2.3.7-2.4)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
Python3 | Lists, Tuples, Dictionaries
Python lists, tuples, dictionaries
How to use lists, tuples, dictionaries, and sets
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Introduction to Python3 Day 23] Chapter 12 Become a Paisonista (12.1 to 12.6)
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
Save lists, dictionaries and tuples to external files python
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python3 Day 10] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.4-5.7)
[Introduction to Python3 Day 9] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.1-5.4)
Introduction to Effectiveness Verification Chapter 1 in Python
[Introduction to Udemy Python3 + Application] 23. How to use tuples
Introduction to effectiveness verification Chapter 3 written in Python
Introduction to Effectiveness Verification Chapter 2 Written in Python
[Chapter 5] Introduction to Python with 100 knocks of language processing
Introduction to Python language
Python> Tuples versus Lists
Introduction to OpenCV (python)-(2)
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
[Chapter 4] Introduction to Python with 100 knocks of language processing
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator